Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Created August 20, 2012 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save FGRibreau/3408240 to your computer and use it in GitHub Desktop.
Save FGRibreau/3408240 to your computer and use it in GitHub Desktop.
Array::until - Return the array elements until a selector is matched #javascript
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);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment