Skip to content

Instantly share code, notes, and snippets.

@silicakes
Last active July 30, 2017 15:20
Show Gist options
  • Save silicakes/7b8076262f2687f1cd154686438895d0 to your computer and use it in GitHub Desktop.
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.
/*
* @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
Copy link

let and = (...fns) => fns.reduce((p, c) => x => p(x) && c(x));

[4,8,16].every(and(isEven, isModuluOf(4), Number.isInteger);

@silicakes
Copy link
Author

silicakes commented Jul 28, 2017

@benjamingr

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