4 ms·
The first is slow (O(n²) where O(n) will do), and the second is very likely to be slow (probably the same).
by Veedrac 9y ago
The first is slow (O(n²) where O(n) will do), and the second is very likely to be slow (probably the same).
- drinchev 9y agoThe good old question about sacrificing performance for readability. Anyway these days filter is not so bad. [1] https://jsperf.com/array-uniq-filter https://jsperf.com/array-uniq-filter
- Veedrac 9y agoAnd insertion sort is not so bad with 20 elements. It doesn't take much for it to start falling over, though. [1]: https://jsperf.com/array-unique-filter-2/1 https://jsperf.com/array-unique-filter-2/1
- _ar7 9y agoIf you wanted to do O(n) functionally, you could do [1, 1, 2, 3, 4].filter( (obj => x => { if (obj[x]) { return false; } obj[x] = true; return true; })({}), ); What's happening is that you're passing an object (hashmap / hashset) into a function that returns a filtering function, and that object is used inside the closure to track the dupes. It's still a pure function because even though you're mutating the passed in object, the filtering function is still deterministic and referentially transparent.