Last active
August 29, 2015 13:59
-
-
Save 0x6a68/10838962 to your computer and use it in GitHub Desktop.
Functional Progamming in Javascript: A checkCommander
This file contains hidden or 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
var slice = Array.prototype.slice; | |
// value to be checked: | |
var value = 1; | |
// limits | |
var max = 100; | |
var min = 10; | |
// checker to create checkCommand on a value | |
var checker = function (/* validators */) { | |
var validators = slice.call(arguments); | |
return function (val) { | |
return validators.map(function (fn) { | |
return fn(val); | |
}).every(function (state) { | |
return state; | |
}); | |
}; | |
}; | |
// validator: return a function with given params | |
var validator = function (fn) { | |
return function () { | |
var args = slice.call(arguments); | |
return function () { | |
return fn.apply(this, args.concat(slice.call(arguments))); | |
}; | |
}; | |
}; | |
// definition of all validators | |
var isMin = validator(function (param, val) { | |
return val >= param; | |
}); | |
var isMax = validator(function (param, val) { | |
return val <= param; | |
}); | |
var isInRange = validator(function (min, max, val){ | |
return isMin(min)(val) && isMax(max)(val); | |
}); | |
var isNumeric = validator(function (val) { | |
return !isNaN(parseFloat(val)) && isFinite(val); | |
}); | |
// actual magic the checkCommand: | |
var checkCommand = checker(isMin(min), isMax(max), isInRange(min, max), isNumeric()); | |
console.log('checkCommand', checkCommand(value)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
demo http://jsbin.com/bacox/2/edit