Created
April 18, 2016 11:04
-
-
Save alihammad-gist/2a920f31b9793943122afdffcac7acc7 to your computer and use it in GitHub Desktop.
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
// merge two sorted arrays | |
// algorithm from | |
// - Sorting by merging, The art of computer programing | |
function merge(x:any[], y:any[]) { | |
const iLen = x.length, | |
jLen = y.length; | |
let i = 0, | |
j = 0, | |
k = 0, | |
z = []; | |
while (i < iLen && j < jLen) { | |
if (x[i] <= y[j]) { | |
z[k] = x[i]; | |
k += 1; | |
i += 1; | |
// goto M2 | |
} else { | |
z[k] = y[j]; | |
k += 1; | |
j += 1; | |
// goto M2 | |
} | |
} | |
if (j < jLen) { | |
z = z.concat( | |
y.slice(j) | |
); | |
} | |
if (i < iLen) { | |
z = z.concat( | |
x.slice(i) | |
); | |
} | |
return z; | |
} | |
function updateInventory(arr1:any[], arr2:any[]) { | |
const compareFn = (a:any[], b:any[]) => { | |
if (a[1] === b[1]) { | |
return 0; | |
} else if (a[1] > b[1]) { | |
return 1; | |
} else { | |
return -1; | |
} | |
} | |
return arr2.sort(compareFn); | |
} | |
// Example inventory lists | |
var curInv = [ | |
[21, "Bowling Ball"], | |
[2, "Dirty Sock"], | |
[1, "Hair Pin"], | |
[5, "Microphone"] | |
]; | |
var newInv = [ | |
[2, "Hair Pin"], | |
[3, "Half-Eaten Apple"], | |
[67, "Bowling Ball"], | |
[7, "Toothpaste"] | |
]; | |
console.log( | |
updateInventory( | |
curInv, | |
newInv | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment