Skip to content

Instantly share code, notes, and snippets.

@RebootJeff
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RebootJeff/c2f9752360591f7b784c to your computer and use it in GitHub Desktop.
Save RebootJeff/c2f9752360591f7b784c to your computer and use it in GitHub Desktop.
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