Created
September 28, 2017 18:00
-
-
Save daviddahl/c377065207c0461e280f095e21714fd4 to your computer and use it in GitHub Desktop.
Implement array sort using splice and for
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
// Using only the Array method Array#splice and the attribute Array#length, please create an array | |
// that is a unique sorted list given the below two lists. | |
var assert = require('assert'); | |
var run_tests = function() { | |
var list1 = [47, 2, 14, 59, 77, 13, 33, 24, 66, 72, 31]; | |
var list2 = [63, 95, 33, 36, 4, 30, 51, 86, 2, 56, 37]; | |
var expected = [ | |
2, 4, 13, 14, 24, 30, 31, 33, 36, 37, 47, 51, 56, 59, 63, 66, 72, 77, 86, 95 | |
]; | |
assert.deepEqual(expected, unique_sorted(list1, list2)); | |
console.log('All tests passed.'); | |
}; | |
var unique_sorted = function(list1, list2) { | |
// fill things in here | |
const longerArr = list1.concat(list2); | |
console.log(longerArr, longerArr.length, list1.length, list2.length); | |
let deDupedArr = [], | |
sortedArr = []; | |
function removeDupes (arr) { | |
let result = []; | |
arr.forEach((item, idx) => { | |
if (result.indexOf(item) == -1) { | |
result.push(item); | |
} | |
}); | |
return result; | |
} | |
function sort (arr) { | |
let sortedArr = []; | |
arr.forEach((item) => { | |
insertValue(item); | |
}); | |
function findIndex (val, arr) { | |
for (var i=0; i<arr.length; i++) { | |
if (arr[i] >= val) { | |
return i; | |
} | |
} | |
return arr.length; | |
} | |
function insertValue (val) { | |
if (!sortedArr.length) { | |
sortedArr.push(val); | |
return; | |
} | |
for (let i = 0; i < sortedArr.length; i++) { | |
let idx = findIndex(val, sortedArr); | |
console.log('find', idx, val, sortedArr); | |
sortedArr.splice(idx, 0, val); | |
return; | |
} | |
} | |
return sortedArr; | |
} | |
deDupedArr = removeDupes(longerArr); | |
sortedArr = sort(deDupedArr); | |
return sortedArr; | |
}; | |
run_tests(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment