Last active
December 20, 2015 23:39
-
-
Save dhruvchandna/6213943 to your computer and use it in GitHub Desktop.
Closures in Javascript to create a mini DSL to filter arrays.
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
var _some = Array.prototype.some; | |
var _every = Array.prototype.every; | |
function lessThan(x){ | |
return function(y){ | |
return y < x; | |
}; | |
} | |
function greaterThan(x){ | |
return function(y){ | |
return y > x; | |
}; | |
} | |
function equalTo(x){ | |
return function(y){ | |
return x === y; | |
} | |
} | |
function or(){ | |
var arr = arguments; | |
return function(x){ | |
return _some.call( | |
arr , function(fn){ | |
return fn(x); | |
} | |
); | |
}; | |
} | |
function and(){ | |
var arr = arguments; | |
return function(x){ | |
return _every.call( | |
arr , function(fn){ | |
return fn(x); | |
} | |
); | |
}; | |
} | |
//USAGE EXAMPLES | |
[1,2,3,1,3].filter( | |
or(lessThan(3), | |
greaterThan(1))); | |
[1,2,3,4,5].filter( | |
and(greaterThan(2), | |
lessThan(4))); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment