How can I make X using Y?
In general, I approach all of these issues the same way: programming languages are not designed for magic wands. If your language does not have a built-in function or behavior, you can write it yourself. From there, if you later find out that your language offers a built-in language for this behavior (or it is added), you can reorganize your code if you want. But by all means, don't sit around waiting for the wand to wave and your code to work magically.
You can use Array.prototype.reduce if you want, but given how it works, it will always Array.prototype.reduce over the entire contents of the array - even if a match is found in the first element. Thus, this means that you should not use Array.prototype.reduce for your function.
However, you can use reduction if you write reduce , which supports early exit. Below is reducek , which passes the continuation to the callback. Applying a continuation will continue, but returning the value will result in an early termination. It seems that exactly what the doctor ordered ...
This answer is intended to accompany LUH3417's answer, to show you that before you can be aware of Array.prototype.some , you should not sit around waiting for ECMAScript to execute your behavior. This answer demonstrates that you can use the reduction procedure and still have early exit behavior.
const reducek = f=> y=> ([x,...xs])=> x === undefined ? y : f (y) (x) (y=> reducek (f) (y) (xs)) const contains = x=> reducek (b=> y=> k=> y === x ? true : k(b)) (false) console.log(contains (4) ([1,2,3,4,5]))
Seeing reducek here and an example of the contains function, it should be somewhat obvious that contains could be generalized, which is Array.prototype.some .
Again, programming is not magic, so I will show you how you could do it if Array.prototype.some does not exist yet.
const reducek = f=> y=> ([x,...xs])=> x === undefined ? y : f (y) (x) (y=> reducek (f) (y) (xs)) const some = f=> reducek (b=> x=> k=> f(x) ? true : k(b)) (false) const contains = x=> some (y=> y === x) console.log(contains (4) ([1,2,3,4,5]))
source share