Is there any way to reinitialize a mapping

Viewed 57

I am trying to code a smart contract and I am using a mapping (address => bool) ; i make it true when a certain conditions meet. Now for another condition I want my mapping to reset and loose all of its data , i want it to be where it was in the beginning a empty mapping.

CODE IMAGE

Problem statement : I am setting all true for whoever voted using in my Dapp using a mapping ( address => bool ) now after voting is ended i want all my mapping values to be false , is there any efficient way to solve this

Thank you in advance..

2 Answers

Now for another condition I want my mapping to reset and loose all of its data , i want it to be where it was in the beginning a empty mapping.

The only way to reset mapping is to iterate through all the keys and set values to zero. This is not practical in Solidity.

Instead, you probably want to use mapping with the third layer and having data tuple of (version, key, value). Then just increment version when you want to do a full reset.

Alternatively you can do (key, version, value) and compare the version every time the key is read. This approach could be more gas efficient, as you are using the same storage lot when rewriting values.

I have found this as most feasible so far;

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;

contract Map {
    mapping (uint => uint)[] array;

    function allocate(uint newMaps) public {
        for (uint i = 0; i < newMaps; i++)
            array.push();
    }

    function writeMap(uint map, uint key, uint value) public {
        array[map][key] = value;
    }

    function readMap(uint map, uint key) public view returns (uint) {
        return array[map][key];
    }

    function eraseMaps() public {
        delete array;
    }
}
Related