Skip to content

Instantly share code, notes, and snippets.

@gecugamo
Last active February 13, 2020 15:42
Show Gist options
  • Save gecugamo/35e70d6067eacc3495c61f16fae7cf4c to your computer and use it in GitHub Desktop.
Save gecugamo/35e70d6067eacc3495c61f16fae7cf4c to your computer and use it in GitHub Desktop.
JS Unique with Recursion (es6)
// unique.js
const unique = (array, newArray = [], index = 0) => {
if (index === array.length) return newArray;
if (!newArray.includes(array[index])) newArray.push(array[index]);
index += 1;
return unique(array, newArray, index);
}
export default unique;
// unique.spec.js
import unique from './unique';
describe('unique', () => {
describe('array with zero elements', () => {
test('returns an empty array', () => {
expect(unique([])).toEqual([]);
});
});
describe('array with one element', () => {
test('returns an array with one element', () => {
expect(unique([1])).toEqual([1]);
});
});
describe('array with more than one element', () => {
test('returns an array with unique elements', () => {
expect(unique([1, 2, 2, 3, 4, 5, 5])).toEqual([1, 2, 3, 4, 5]);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment