r/javascript • • Oct 12 '19

TIL — The power of JSON.stringify replacer parameter

https://pawelgrzybek.com/til-the-power-of-json-stringify-replacer-parameter/
378 Upvotes

42 comments sorted by

View all comments

Show parent comments

9

u/TheFundamentalFlaw Oct 12 '19

I'm a seasoned Js Dev but I never really understood Sets, Weaksets and so on. Why and when would I use these kind of data structures? For me, I can always get away just with objects and arrays.

0

u/[deleted] Oct 12 '19

[deleted]

-2

u/leixiaotie Oct 12 '19

Huh, TIL. Usually using lodash.uniqBy for that. Hoping if the future ECMA added arr.uniq or arr.distinct natively.

2

u/helloiamsomeone Oct 12 '19
const distinct = iterable => [...new Set(iterable)];

const uniqBy = (iterable, mapper) => {
  const result = [];
  const mapSet = new Set();
  
  for (const value of iterable) {
    const mappedValue = mapper(value);
    
    if (!mapSet.has(mappedValue)) {
      mapSet.add(mappedValue);
      result.push(value);
    }
  }
  
  return result;
};

That was easy