Last active
December 22, 2015 11:09
-
-
Save tomgullo/6464043 to your computer and use it in GitHub Desktop.
merge_lists_of_lists
This file contains 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
function process(result, val, temp_val) { | |
var inner_val = isNaN(val) ? val : [val, val]; | |
if (temp_val.length == 0) { //no temp | |
temp_val = inner_val; | |
} else if ( (inner_val[1] -1) > temp_val[1] ) { //flush temp | |
if (temp_val[0] == temp_val[1]) { | |
result.push(temp_val[0]); | |
} else { | |
result.push(temp_val[0] + '-' + temp_val[1]); | |
} | |
temp_val = inner_val; | |
} else { | |
temp_val[1] = inner_val[1]; | |
} | |
return temp_val; | |
} | |
function isNumber(num) { return !isNaN(num) } | |
function merge(left, right){ | |
var result = [], | |
temp_val = [], | |
il = 0, | |
ir = 0; | |
while (il < left.length && ir < right.length){ | |
var left_val = isNumber(left[il]) ? left[il]: left[il][0]; | |
var right_val = isNumber(right[ir]) ? right[ir] : right[ir][0]; | |
if (left_val < right_val){ //process left | |
temp_val = process(result, left[il++], temp_val) | |
} else { //process right | |
temp_val = process(result, right[ir++], temp_val) | |
} | |
} | |
var ls = left.slice(il); | |
for(var b = 0; b < ls.length; b++) { | |
temp_val = process(result, ls[b], temp_val) | |
} | |
var rs = right.slice(ir); | |
for(var c = 0; c < rs.length; c++, temp_val) { | |
temp_val = process(result, rc[c]) | |
} | |
if (temp_val.length > 0) { | |
if (temp_val[0] == temp_val[1]) { | |
result.push(temp_val[0]); | |
} else { | |
result.push(temp_val[0] + '-' + temp_val[1]); | |
} | |
} | |
return result; | |
} | |
var r = merge([[2,3],4,6,8,10,20], [3,[4,4],8,[13,14],16,18]).toString(); | |
r | |
/* | |
2-4,6,8,10,13-14,16,18,20 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment