欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iterMap

程序员文章站 2022-03-25 11:36:24
...
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;

struct KeyStruct {
    string key;
    bool deleted;
}

struct ValueStruct {
    string value;
    bool isValue;
    uint index; //删除的时候会用到
}

contract IteratorMap{
    mapping(string => ValueStruct) dataMap;
    KeyStruct[] keyArr;
    constructor(){

    }

    function insert(string memory k,string memory v) external returns (bool){
        if (dataMap[k].isValue){
            return false;
        }
        uint i = keyArr.length;
        dataMap[k] = ValueStruct({value:v,isValue:true,index:i});
        keyArr.push();
        keyArr[i] = KeyStruct({key:k,deleted:false});
        return true;
    }

    function del(string memory k) external {
        require(dataMap[k].isValue);
        delete keyArr[dataMap[k].index]; 
        delete dataMap[k];
    }

    function display() external view returns(string[] memory){
        string[] memory data;
        data = new string[](keyArr.length);
        uint j = 0;
        for (uint i=0;i<keyArr.length;i++){
            if (dataMap[keyArr[i].key].isValue) {
                data[j] = dataMap[keyArr[i].key].value;
                j++;
            }
        }
        return data;
    }
}


const { expect } = require("chai");
const { ethers } = require("hardhat");


describe("contract", function () {
  it("test", async function () {
    const MyContract = await ethers.getContractFactory("IteratorMap");
    const myContract = await MyContract.deploy();
    await myContract.deployed();
    await myContract.insert("6","6");
    await myContract.insert("60","60");
    await myContract.insert("600","600");
    result = await myContract.display();
    console.log("result:",result)
    await myContract.del("60");
    result = await myContract.display();
    console.log("result:",result)
  });
});



  contract
result: [ '6', '60', '600' ]
result: [ '6', '600', '' ]

推荐阅读