Skip to content

Instantly share code, notes, and snippets.

@0x6a68
Last active August 29, 2015 13:59
Show Gist options
  • Save 0x6a68/10838962 to your computer and use it in GitHub Desktop.
Save 0x6a68/10838962 to your computer and use it in GitHub Desktop.
Functional Progamming in Javascript: A checkCommander
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));
@0x6a68
Copy link
Author

0x6a68 commented Apr 16, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment