Copy codeThe Code is as follows:
/*!
* JLip JavaScript Library v0.1
*
* Copyright 2012, Lip2up (lip2up@qq.com)
* Just for free use, NO LICENSE
*/
(Function (){
Function extend (target, props ){
For (var m in props ){
If (target [m] === undefined) target [m] = props [m];
}
}
Var fns = {every: 1, some: 2, forEach: 3, map: 4, filter: 5 },
Performanceerror = 'reduce of empty array with no initial value ';
Function each (fn, _ this, kind ){
Var len = this. length, ret = kind = fns. filter? []
: Kind = fns. map? Array (len): undefined,
Find = kind = fns. some, I, v;
For (I = 0; I <len; I ++ ){
If (this [I]! = Undefined ){
V = fn. call (_ this, this [I], I, this );
Switch (kind ){
Case fns. every:
Case fns. some:
If (v = find) return find;
Break;
Case fns. map:
Ret [I] = v;
Break;
Case fns. filter:
If (v = true) ret [ret. length] = this [I];
Break;
}
}
}
Return kind> = fns. forEach? Ret :! Find;
}
Function reduce (fn, init, right ){
Var len = this. length, I, prev, inc = right? -1: 1;
If (len = 0 & init = undefined)
Throw TypeError (reduceError );
For (I = right? Len-1: 0, prev = init;
Prev === undefined & (right? I> = 0: I <len );
I + = inc ){
Prev = this [I];
}
If (prev = undefined & I = (right? -1: len ))
Throw TypeError (reduceError );
For (; (right? I> = 0: I <len); I + = inc ){
If (this [I]! = Undefined)
Prev = fn (prev, this [I], I, this );
}
Return prev;
}
Extend (Array. prototype ,{
Every: function (fn, _ this ){
Return each. call (this, fn, _ this, fns. every );
},
Some: function (fn, _ this ){
Return each. call (this, fn, _ this, fns. some );
},
ForEach: function (fn, _ this ){
Return each. call (this, fn, _ this, fns. forEach );
},
Map: function (fn, _ this ){
Return each. call (this, fn, _ this, fns. map );
},
Filter: function (fn, _ this ){
Return each. call (this, fn, _ this, fns. filter );
},
Reduce: function (fn, init ){
Return reduce. call (this, fn, init );
},
ReduceRight: function (fn, init ){
Return reduce. call (this, fn, init, true );
}
});
})();