Last Updated: February 25, 2016
·
465
· FGRibreau

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);
  }
});