Return the array elements until a selector is matched
Object.defineProperty(Array.prototype, 'until',{
/**
* Return the array elements until a selector is matched
* @param {Number|String|Function} selector
* @return {Array} A new array that goes from the first element to `selector`
*
* Usage:
* deepEqual([1,2,3,4,5].until(4), [1, 2, 3, 4])
* deepEqual(['a','b','c','d','e'].until('c'), ['a', 'b', 'c'])
* deepEqual([{t:'a'},{t:'b'},{t:'c'},{t:'d'}].until(function(o){return o.t == 'c';}), [{t:'a'},{t:'b'},{t:'c'}])
*
* Note:
* Array as selector aren't supported for code brevity. Yet type coercion will work (of course).
*/
value:function(selector){
var m = this.length, i = 0;
fn = !selector
? function(){return true;}
: (
typeof selector !== 'function'
? function(x){return x == selector;}
: selector
);
while(!fn(this[i]) && i++ < m);
return this.slice(0, i+1);
}
});Written by Francois-Guillaume Ribreau
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#