Last active
June 21, 2016 23:02
-
-
Save juniorbird/1ee508142073e347bdcbf5ed77043cc6 to your computer and use it in GitHub Desktop.
Reducing and composing in Javascript
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
'use strict'; | |
function sortedCal(calArray) { | |
return calArray.sort((a, b) => a[0] > b[0]); | |
} | |
function mergeRanges(sortedCal) { | |
let start; | |
let end; | |
let last; | |
return sortedCal.reduce((merged, currEvent) => { | |
last = merged.length - 1; | |
if (currEvent[0] <= merged[last][1]) { | |
start = merged[last][0]; | |
if (currEvent[1] > merged[last][1]) { | |
end = currEvent[1]; | |
} else { | |
end = merged[last][1]; | |
} | |
merged[last] = [start, end]; | |
} else { | |
merged.push(currEvent); | |
} | |
return merged; | |
}, [sortedCal[0]]); | |
} | |
function rangeHours(mergedCal) { | |
return mergedCal.reduce((merged, event) => { | |
merged.push([event[1] - event[0]]); | |
return merged; | |
}, []); | |
} | |
function compose() { | |
let f2; | |
const args = [...arguments]; | |
return function() { | |
return args.reduce((accum, fx) => { | |
f2 = fx.apply(null, accum); | |
return [f2]; | |
}, [...arguments]); | |
}; | |
} | |
const cal = [[3, 4], [9, 12], [1, 3], [6, 8], [9, 10]]; | |
compose(sortedCal, mergeRanges, rangeHours, f => console.log(f))(cal); // [[3, 2, 3]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment