Created
September 22, 2015 14:06
-
-
Save NeoTech/0b184e0050b64bdfd34c to your computer and use it in GitHub Desktop.
Short explanation of currying and its uses. And maybe pitfalls.
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
/** | |
This creates a factory with the objective to make less code for repetitive tasks. | |
Normal way would have been to code each of these functions individually. | |
Instead we createa currying function that acts as a factory. | |
**/ | |
function UnitConversion() { | |
// Takes single object. | |
var args = Array.prototype.slice.call(arguments); | |
if(args[0].length > 0) { | |
// Handle if input is an array of objects. | |
args = Array.prototype.slice.call(arguments[0]); | |
} | |
for(var x in args) { | |
UnitConversion.prototype[args[x].name] = UnitConversion.prototype.converter(args[x].unit,args[x].factor); | |
} | |
} | |
// Creating universal converter. | |
UnitConversion.prototype.converter = function(toUnit,factor) { | |
return function (input,offset) { | |
offset = offset || 0; | |
return [((offset+input)*factor).toFixed(2), toUnit].join(" ").trim(); | |
} | |
} | |
var convert = new Array(); | |
convert.push({"name":"milesToKm","unit":"km","factor":"1.60936"}); | |
convert.push({"name":"inchToCm","unit":"cm","factor":"2.54"}); | |
var u = new UnitConversion(convert); | |
console.log(u.milesToKm(10)); | |
console.log(u.inchToCm(10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment