ES6 Card: Conversion Values

I am working on a project where I often have to convert each value to an ES6 card:

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

Just wondering if there could be a better way to do this? Ideally, one liner, for example Array.map().

Bonus points (actually) if they are compiled in typescript!

+4
source share
3 answers

You can use the Array.from2 nd map-style callback argument :

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

console.log([...negativeMap]);
Run codeHide result
+4
source

You can convert it to an array using propagation syntax ..., apply a method map(), and then convert it back toMap

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

const negativeMap = new Map([...positiveMap].map(([k, v]) => [k, v * -1]))
console.log([...negativeMap])
Run codeHide result
+3
source

, 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));
Hide result

I quit reduce(), every()and some()for free. Implement as many or more methods that you like or need.

+1
source

Source: https://habr.com/ru/post/1693043/


All Articles