Skip to content

Instantly share code, notes, and snippets.

@taku0
Created September 19, 2016 13:08
Show Gist options
  • Save taku0/82465ec122faf4b06abf2288e98fa753 to your computer and use it in GitHub Desktop.
Save taku0/82465ec122faf4b06abf2288e98fa753 to your computer and use it in GitHub Desktop.
// http://qiita.com/bellbind/items/50954258e262fd7c6bd1
function uniq1(A, i = 0, r = [], h = A[i], l = r.length) {
if (i === A.length) return r;
return uniq1(A, i + 1, l === 0 ? [h] : h === r[l - 1] ? r : [...r, h]);
}
function uniq2(array) {
const result = [];
for (let i = 0; i < array.length; i++) {
if (i === 0 || array[i - 1] !== array[i]) {
result.push(array[i]);
}
}
return result;
}
function uniq3(A) {
let r = [];
for (let i = 0; i < A.length; i++) {
const l = r.length;
const h = A[i];
if (l === 0) {
r = [h];
} else if (r[l - 1] !== h) {
r = [...r, h];
}
}
return r;
}
(function() {
var array = [];
for (let i = 0; i < 1000; i++) {
array.push((Math.random() * 100)|0);
}
array.sort();
const start = new Date().getTime();
let sum = 0;
for (let i = 0; i < 100; i++) {
sum += uniq3(array).length;
}
const end = new Date().getTime();
console.log(sum, end - start);
})();
console.log(uniq1([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])); //=> [1, 2, 3, 4]
console.log(uniq2([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])); //=> [1, 2, 3, 4]
console.log(uniq1([undefined, undefined, undefined])); //=> [undefined]
console.log(uniq2([undefined, undefined, undefined])); //=> [undefined]
// Firefox 48.0.2
// uniq2: 2772 ms
// uniq3: 204 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment