How to display / reduce / filter a set in JavaScript?

Is there a way map/ reduce/ filter/ etc a Setin JavaScript or do I need to write my own?

Here are some reasonable extensions Set.prototype

Set.prototype.map = function map(f) {
  var newSet = new Set();
  for (var v of this.values()) newSet.add(f(v));
  return newSet;
};

Set.prototype.reduce = function(f,initial) {
  var result = initial;
  for (var v of this) result = f(result, v);
  return result;
};

Set.prototype.filter = function filter(f) {
  var newSet = new Set();
  for (var v of this) if(f(v)) newSet.add(v);
  return newSet;
};

Set.prototype.every = function every(f) {
  for (var v of this) if (!f(v)) return false;
  return true;
};

Set.prototype.some = function some(f) {
  for (var v of this) if (f(v)) return true;
  return false;
};

Take a small set

let s = new Set([1,2,3,4]);

And some silly little features

const times10 = x => x * 10;
const add = (x,y) => x + y;
const even = x => x % 2 === 0;

And look how they work.

s.map(times10);    //=> Set {10,20,30,40}
s.reduce(add, 0);  //=> 10
s.filter(even);    //=> Set {2,4}
s.every(even);     //=> false
s.some(even);      //=> true

Isn't that nice? Yes, I think so too. Compare this to the ugly use of an iterator

// puke
let newSet = new Set();
for (let v in s) {
  newSet.add(times10(v));
}

and

// barf
let sum = 0;
for (let v in s) {
  sum = sum + v;
}

Is there a better way to execute mapand reduceusing Setin JavaScript?

+35
source share
3 answers

A short way to do this is to convert it to an array using the ES6 distribution operator.

.

const mySet = new Set([1,2,3,4]);
[...mySet].reduce()
+17

: reduce, , , ES7.

map, Set, .

(a) => 42 - 1, , .

, , , , map reduce, (, Set ), , . Array .

+10

map/reduce/filter map/Set . Javascript ,

const mySet = new Set([1,2,3]);
const myMap = new Map([[1,1],[2,2],[3,3]]);

mySet.map(x => x + 1);
myMap.map(([k, x]) => [k, x + 1]);

new Set(Array.from(mySet.values(), x => x + 1));
new Map(Array.from(myMap.entries(), ([k, x]) => [k, x + 1]));

An alternative was to specify map / reduce / filter as part of the / iterator iterator protocol since entries/ values/ keysreturn Iterators. Of course, although not everyone is iterable, they are also “mapped”. Another alternative was to specify a separate “collection protocol” for this very purpose.

However, I do not know the current discussion on this topic in ES.

+3
source

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


All Articles