4

我正在做一个项目,我经常需要转换 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().

加分(不是真的),如果它在打字稿中编译!

4

4 回答 4

5

你可以使用Array.from第二个参数,一个地图风格的回调:

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

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

于 2018-02-01T20:24:47.063 回答
3

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

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

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

于 2018-02-01T20:20:30.420 回答
1

如果需要,您可以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()是免费的。实施尽可能多或尽可能少的您喜欢或需要的方法。

于 2018-02-01T20:36:43.470 回答
0

你可以有一个基于 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)
于 2020-06-06T21:04:49.457 回答