class ArrayMap extends Map {
map (fn, thisArg) {
const { constructor: Map } = this;
const map = new Map();
for (const [key, value] of this.entries()) {
map.set(key, fn.call(thisArg, value, key, this));
}
return map;
}
forEach (fn, thisArg) {
for (const [key, value] of this.entries()) {
fn.call(thisArg, value, key, this);
}
}
reduce (fn, accumulator) {
const iterator = this.entries();
if (arguments.length < 2) {
if (this.size === 0) throw new TypeError('Reduce of empty map with no initial value');
accumulator = iterator.next().value[1];
}
for (const [key, value] of iterator) {
accumulator = fn(accumulator, value, key, this);
}
return accumulator;
}
every (fn, thisArg) {
for (const [key, value] of this.entries()) {
if (!fn.call(thisArg, value, key, this)) return false;
}
return true;
}
some (fn, thisArg) {
for (const [key, value] of this.entries()) {
if (fn.call(thisArg, value, key, this)) return true;
}
return false;
}
}
const positiveMap = new ArrayMap(
[
['hello', 1],
['world', 2]
]
);
const negativeMap = positiveMap.map(value => -value);
negativeMap.forEach((value, key) => console.log(key, value));