Last active
August 29, 2015 14:15
-
-
Save RebootJeff/c2f9752360591f7b784c to your computer and use it in GitHub Desktop.
Function composition for type conversion
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 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