ES6 Map:转换值

ES6 Map: transform values

我正在做一个项目,我经常需要转换 ES6 映射中的每个值:

const positiveMap = new Map(
  [
    ['hello', 1],
    ['world', 2]
  ]
);

const negativeMap = new Map<string, number>();
for (const key of positiveMap.keys()) {
  negativeMap.set(key, positiveMap.get(key) * -1);
}

只是想知道是否有更好的方法?理想情况下像 Array.map().

这样的单行

奖励积分(不是真的),如果它用打字稿编译!

您可以使用扩展语法 ... 将其转换为数组,应用 map() 方法,然后再次将其转换为 Map

const positiveMap = new Map([['hello', 1],['world', 2]]);

const negativeMap = new Map([...positiveMap].map(([k, v]) => [k, v * -1]))
console.log([...negativeMap])

您可以使用 Array.from 2nd 参数,地图样式回调:

const positiveMap = new Map([['hello', 1],['world', 2]]),
    negativeMap = new Map(Array.from(positiveMap, ([k, v]) => [k, -v]));

console.log([...negativeMap]);

如果需要,您可以使用自己的 class 扩展 Map 并包含像数组一样对其进行一般迭代的功能:

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));

我免费投入了 reduce()every()some()。实现您喜欢或需要的任意数量的方法。

你可以根据 trincot 的回答得到一个通用的打字稿函数

function transformMap<K, V, U>(source: Map<K, V>, func: (key: K, value: V) => U): Map<K, U> {
  return new Map(Array.from(source, (v) => [v[0], func(v[0], v[1])]));
}

并像这样使用它

transformMap(positiveMap, (key, value) => -value)