Last change
on this file since 6c1585f was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.1 KB
|
Line | |
---|
1 | 'use strict';
|
---|
2 |
|
---|
3 | // there's 3 implementations written in increasing order of efficiency
|
---|
4 |
|
---|
5 | // 1 - no Set type is defined
|
---|
6 | function uniqNoSet(arr) {
|
---|
7 | var ret = [];
|
---|
8 |
|
---|
9 | for (var i = 0; i < arr.length; i++) {
|
---|
10 | if (ret.indexOf(arr[i]) === -1) {
|
---|
11 | ret.push(arr[i]);
|
---|
12 | }
|
---|
13 | }
|
---|
14 |
|
---|
15 | return ret;
|
---|
16 | }
|
---|
17 |
|
---|
18 | // 2 - a simple Set type is defined
|
---|
19 | function uniqSet(arr) {
|
---|
20 | var seen = new Set();
|
---|
21 | return arr.filter(function (el) {
|
---|
22 | if (!seen.has(el)) {
|
---|
23 | seen.add(el);
|
---|
24 | return true;
|
---|
25 | }
|
---|
26 |
|
---|
27 | return false;
|
---|
28 | });
|
---|
29 | }
|
---|
30 |
|
---|
31 | // 3 - a standard Set type is defined and it has a forEach method
|
---|
32 | function uniqSetWithForEach(arr) {
|
---|
33 | var ret = [];
|
---|
34 |
|
---|
35 | (new Set(arr)).forEach(function (el) {
|
---|
36 | ret.push(el);
|
---|
37 | });
|
---|
38 |
|
---|
39 | return ret;
|
---|
40 | }
|
---|
41 |
|
---|
42 | // V8 currently has a broken implementation
|
---|
43 | // https://github.com/joyent/node/issues/8449
|
---|
44 | function doesForEachActuallyWork() {
|
---|
45 | var ret = false;
|
---|
46 |
|
---|
47 | (new Set([true])).forEach(function (el) {
|
---|
48 | ret = el;
|
---|
49 | });
|
---|
50 |
|
---|
51 | return ret === true;
|
---|
52 | }
|
---|
53 |
|
---|
54 | if ('Set' in global) {
|
---|
55 | if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
|
---|
56 | module.exports = uniqSetWithForEach;
|
---|
57 | } else {
|
---|
58 | module.exports = uniqSet;
|
---|
59 | }
|
---|
60 | } else {
|
---|
61 | module.exports = uniqNoSet;
|
---|
62 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.