Created
May 15, 2015 21:28
-
-
Save isRuslan/f9bb23b0ce4d393990cc to your computer and use it in GitHub Desktop.
JS: unique array
This file contains hidden or 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
| // O(n^2): loop in loop | |
| function unique_one (array) { | |
| var result = []; | |
| for (var i = 0; i < array.length; i++) { | |
| for (var j = i; j < array.length; j++) { | |
| if (array[i] == array[j]) { | |
| // mmmm | |
| } | |
| } | |
| result.push(array[i]) | |
| } | |
| return result; | |
| } | |
| // O(n): loop + hash | |
| function unique_two () { | |
| var result = []; | |
| return result; | |
| } | |
| // test | |
| var assert = require('assert'); | |
| var data = [ | |
| { should:[0, 1, 1, 2], toBe: [0, 1, 2] }, | |
| { should:[2, 1, 0, 0], toBe: [2, 1, 0] }, | |
| { should:[1, 1, 1], toBe: [1] }, | |
| { should:[0], toBe: [0] } | |
| ]; | |
| console.log('unique_one'); | |
| data.forEach(function (it) { | |
| var should = unique_one(it.should); | |
| assert.deepEqual( | |
| should, it.toBe, | |
| should + ' should equal ' + it.toBe | |
| ); | |
| }); | |
| console.log('unique_two'); | |
| data.forEach(function (it) { | |
| var should = unique_two(it.should); | |
| assert.deepEqual( | |
| should, it.toBe, | |
| should + ' should equal ' + it.toBe | |
| ); | |
| }); | |
| console.log('all passed'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment