-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
export default function uniques (list, iteratee, transform = false) { | ||
if (!Array.isArray(list)) { | ||
console.error('LayerCake error: Input value to `uniques` must be a list.'); | ||
return null; | ||
}; | ||
const ll = list.length; | ||
const iterater = typeof iteratee === 'function'; | ||
const key = typeof iteratee !== 'undefined'; | ||
const seen = []; | ||
const result = []; | ||
for (let i = 0; i < ll; i++) { | ||
const d = list[i]; | ||
const computed = iterater ? iteratee(d) : key === true ? d[iteratee] : d; | ||
if (!seen.includes(computed)) { | ||
seen.push(computed); | ||
if (transform === false) { | ||
result.push(d); | ||
} | ||
} | ||
} | ||
return transform === false ? result : seen; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/* globals describe it */ | ||
import uniques from '../src/lib/uniques.js'; | ||
import * as assert from 'assert'; | ||
|
||
const name = 'uniques'; | ||
|
||
const tests = [ | ||
{ args: [0], expected: null }, | ||
{ args: [[0]], expected: [0] }, | ||
{ args: [[0, 0, 1]], expected: [0, 1] }, | ||
{ args: [['a', 'b', 'b', 'c']], expected: ['a', 'b', 'c'] }, | ||
{ args: [['a', 1, 'b', 1]], expected: ['a', 1, 'b'] }, | ||
{ | ||
args: [ | ||
[{x: 1, b: 2}, {x: 1, b: 3}, {x: 2, b: 4}], | ||
'x' | ||
], | ||
expected: [{x: 1, b: 2}, {x: 2, b: 4}] | ||
}, | ||
{ | ||
args: [ | ||
[{x: 1, b: 2}, {x: 1, b: 3}, {x: 2, b: 4}], | ||
'x', | ||
true | ||
], | ||
expected: [1, 2] | ||
}, | ||
{ | ||
args: [ | ||
[{x: 1, b: 2}, {x: 1, b: 3}, {x: 2, b: 4}], | ||
d => d.x, | ||
true | ||
], | ||
expected: [1, 2] | ||
} | ||
]; | ||
|
||
describe(name, function () { | ||
tests.forEach(test => { | ||
describe(JSON.stringify(test.args), function () { | ||
it(`should equal ${JSON.stringify(test.expected)}`, function () { | ||
const actual = uniques(...test.args); | ||
assert.deepStrictEqual(actual, test.expected); | ||
}); | ||
}); | ||
}); | ||
}); |