javascript - How to solve _.some using _.every? -
working on programming challenge re-implement functionality of underscore.js in standard javascript. working on implementing _.some
function. (http://underscorejs.org/#some) part i'm struggling it's asking me find way solve using _.every
internally. (http://underscorejs.org/#every)
i have finished _.every
function earlier , works should.
here logically wanting in sketched code:
_.some = function(collection, truthstatementfunction) { return !(_every(collection, !truthstatementfunction)) }
or in english, flip truth statement test condition false... , if _.every
test returns true... know _.some of original truth statement false (so flip return of _.every
correct return _some
). likewise if _.every
returns false flip correct return of true _.some
.
obviously problem sketch !truthstatementfunction
part. how inside iterator change internals of function flip it? doesn't seem internals of function accessible...
am barking wrong tree entirely, , there better way solve using _.every
?
pass _every
function returns inversion of result truthstatementfunction
:
_.some = function(collection, truthstatementfunction) { return !(_every(collection, function(v) { return !truthstatementfunction(v); })); }
to answer second part of question:
and there better way solve using _.every?
there better way solve using _.every
. iterate on collection, , return true find element matches. more efficient in cases _.some
going return true, since don't care how many elements in collection satisfy predicate, long there @ least one.
_.some = function(c, pred) { for(var = 0; < c.length; i++) { if (pred(c[i])) return true; } return false; }
Comments
Post a Comment