Last active
July 30, 2017 15:20
-
-
Save silicakes/7b8076262f2687f1cd154686438895d0 to your computer and use it in GitHub Desktop.
Takes a set of predicates and returns a function f that returns true if all of its composing predicates return a logical true value against all of its arguments.
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
/* | |
* @description | |
* ported from Clojure's own [(every-pred)](https://clojuredocs.org/clojure.core/every-pred) | |
* array.everyPred(pred0, pred1...predN) | |
* | |
* From Clojure's documentation: | |
* Takes a set of predicates and returns a function f that returns true if all of its composing predicates return a logical true | |
* value against all of its arguments, else it returns false. | |
* Note that f is short-circuiting in that it will stop execution on the first argument that triggers a - | |
* logical false result against the original predicates. | |
* @params | |
* any number of [predicate functions](https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)) | |
*/ | |
Array.prototype.everyPred = function(...predFns) { | |
return predFns.every(fn => this.every(fn)); | |
} | |
let isEven = val => !(val%2); | |
let isModuloOf = modulo => val => !(val%modulo); | |
let t = [4,8,16].everyPred(Number.isInteger, isEven, isModuloOf(4)); // true |
benjamingr
commented
Jul 26, 2017
TL;DR
Your approach doesn't short-circuit.
I see the point in not touching the prototype, but you can achieve the same with something like everyPred(arr, ...predFns)
.
Although false && true
will only evaluate the left hand of the expression, the reduction loop will continue until the end of the array even if one of them might be evaluated as false, contrary to every
- which will break on the first falsy result, which, depends on the case - can optimize the loops average complexity.
Still, I love your approach as an additional feature, and would love to hear your comment about this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment