Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Function composition for type conversion
function makeConverter(pairs) {
function converter(value) {
for(var i = 0; i < pairs.length; i++) {
var predicate = pair[0];
var func = pair[1];
if(predicate(value)) {
return converter(func(value));
// if no predicate is satisfied, then just return original value
return value;
return converter;
// `convertColor` will be smart enough to know which conversion to perform based on input type
convertColor = makeConverter([
[isColorName, colorNameToHex],
[is256Color, color256ToHex], // this pair plus next pair can lead to converting 256 to Name if untilFixedPoint is used
[isHexColor, colorHexToName]
convertColor('green') == colorNameToHex('green');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment