Last active
December 26, 2020 13:51
-
-
Save prashant1k99/573a1fa9a60e8ee988f93c553be4a96b to your computer and use it in GitHub Desktop.
Polyfill for the Map in Js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BetterMap { | |
constructor(init) { | |
this.clear() | |
if (init) | |
for (var i = 0; i < init.length; i++) | |
this.set(init[i][0], init[i][1]) | |
} | |
clear() { | |
this._map = {} | |
this._keys = [] | |
this.size = 0 | |
} | |
get(key) { | |
return this._map["map_" + key] | |
} | |
set(key, value) { | |
this._map["map_" + key] = value | |
if (this._keys.indexOf(key) < 0) | |
this._keys.push(key) | |
this.size = this._keys.length | |
return this | |
} | |
has(key) { | |
return this._keys.indexOf(key) >= 0 | |
} | |
delete(key) { | |
var idx = this._keys.indexOf(key) | |
if (idx < 0) | |
return false | |
delete this._map["map_" + key] | |
this._keys.splice(idx, 1) | |
this.size = this._keys.length | |
return true | |
} | |
keys() { | |
return { | |
_keys: this._keys, | |
_idx: 0, | |
next: function () { | |
if (this._idx < this._keys.length) | |
return { | |
value: this._keys[this._idx++], | |
done: false | |
} | |
return { | |
value: undefined, | |
done: true | |
} | |
} | |
} | |
} | |
forEach(callback, thisArg) { | |
for (var i = 0; i < this._keys.length; i++) | |
callback.call(thisArg, this._map["map_" + this._keys[i]], this._keys[i], this) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment