Last active
August 29, 2015 14:17
-
-
Save formula1/eb2617d5f8e7f7f7febf to your computer and use it in GitHub Desktop.
Merging Arrays
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
function mergeUnIntersectingLists(lists, sortFn, order,iterator){ | |
standardIterator(lists, sortFn, order,iterator,function(lists,order,i){ | |
while(lists[i].length > 0){ | |
var item = getOrder(lists[i],sortFn)==order?lists[i].shift():lists[i].pop(); | |
iterator(item,i); | |
} | |
lists.splice(i,1); | |
}); | |
} | |
function mergeIntersectingLists(lists, sortFn, order,iterator){ | |
standardIterator(lists, sortFn, order,iterator,function(lists,order,i){ | |
var item = getOrder(lists[i],sortFn)==order?lists[i].shift():lists[i].pop(); | |
iterator(item,i); | |
if(lists[i].length === 0){ | |
lists.splice(i,1); | |
} | |
}); | |
} | |
function standardIterator(lists, sortFn, order,iterator, listFn){ | |
iterator = handleIterator(iterator); | |
if(typeof order === "number") order = getOrder(lists[order],sortFn); | |
if(!order) order = 1; | |
listFn = listFn.bind(void(0),lists,order); | |
while(var l=lists.length){ | |
reduceLists(lists,l,sortFn).forEach(listFn); | |
} | |
} | |
function reduceLists(lists,listLength,order,sortFn){ | |
var next = []; | |
var extra = false; | |
for(var a=0,b=1;b<listLength;b++){ | |
if(b === a) continue; | |
var curOrder = getListOrder(sortFn,order,lists,a,b); | |
curOrder = curOrder<0:-1:curOrder>0:1:0; | |
if(curOrder != order){ | |
next.unshift(b); | |
a = b | |
extra = true | |
}else if(extra){ | |
next = [a]; | |
extra = false; | |
} | |
} | |
return next; | |
} | |
function getOrder(list,sortFn){ | |
return list.length < 2?0:sortFn(list[0],list[1]); | |
} | |
function handleIterator(iterator){ | |
if(Array.isArray(iterators)){ | |
return function(item,i){ | |
iiterator[a](item); | |
}; | |
}else if(typeof iterators == "function"){ | |
return iterator; | |
} | |
throw new Error("need to provide an iterator that is a function or an array"); | |
} | |
function getListOrder(sortFn,order,lists,a,b){ | |
a = getOrder(lists[a],sortFn)==order?lists[a][0]:lists[a][list[a].length-1]; | |
b = getOrder(lists[b],sortFn)==order?lists[b][0]:lists[b][list[b].length-1]; | |
return sortFn(a,b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment