Skip to content

Commit

Permalink
add uniques.js
Browse files Browse the repository at this point in the history
  • Loading branch information
mhkeller committed Oct 20, 2018
1 parent 0131a28 commit b4c768c
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/lib/uniques.js
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;
}
47 changes: 47 additions & 0 deletions test/uniques.js
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);
});
});
});
});

0 comments on commit b4c768c

Please sign in to comment.