jquery.enumerable.js (3038B)
1 (function ( $ ) { 2 var methods = { 3 // $([1,2,3]).collect(function() { return this * this }) // => [1, 4, 9] 4 collect: function(enumerable, callback) { 5 var result = []; 6 $.each(enumerable, function(index) { 7 result.push(callback.call(this, index)); 8 }); 9 return result; 10 }, 11 12 // $([1,2,3]).inject(0, function(a) { return a + this }) // => 6 13 inject: function(enumerable, initialValue, callback) { 14 var accumulator = initialValue; 15 16 $.each(enumerable, function (index) { 17 accumulator = callback.call(this, accumulator, index); 18 }); 19 return accumulator; 20 }, 21 22 // $([1,2,3]).select(function() { return this % 2 == 1 }) // => [1, 3] 23 select: function(enumerable, callback) { 24 var result = []; 25 $.each(enumerable, function(index) { 26 if (callback.call(this, index)) 27 result.push(this); 28 }); 29 return result; 30 }, 31 32 // $([1,2,3]).reject(function() { return this % 2 == 1 }) // => [2] 33 reject: function(enumerable, callback) { 34 return $.select(enumerable, negate(callback)); 35 }, 36 37 // $([1,2]).any(function() { return this == 1 }) // => true 38 any: function(enumerable, callback) { 39 return $.inject(enumerable, false, function(accumulator, index) { 40 return accumulator || callback.call(this, index); 41 }); 42 }, 43 44 // $([1,1]).any(function() { return this == 1 }) // => true 45 all: function(enumerable, callback) { 46 return $.inject(enumerable, true, function(accumulator, index) { 47 return accumulator && callback.call(this, index); 48 }); 49 }, 50 51 // $([1,2,3]).sum() // => 6 52 sum: function(enumerable) { 53 return $.inject(enumerable, 0, function(accumulator) { 54 return accumulator + this; 55 }); 56 } 57 }; 58 59 var staticFunctions = {}; 60 var iteratorFunctions = {}; 61 $.each( methods, function(name, f){ 62 staticFunctions[name] = makeStaticFunction(f); 63 iteratorFunctions[name] = makeIteratorFunction(staticFunctions[name]); 64 }); 65 $.extend(staticFunctions); 66 $.fn.extend(iteratorFunctions); 67 68 // Private methods 69 function makeStaticFunction(f) { 70 return function() { 71 if (arguments.length > 1) // The first argument is the enumerable 72 validateCallback(arguments[arguments.length - 1]); 73 74 return f.apply(this, arguments); 75 } 76 } 77 78 function makeIteratorFunction(staticFunction) { 79 return function() { 80 // arguments isn't a real array, concat doesn't work 81 // unless you explicitly convert it 82 function toArray() { 83 var result = [] 84 for (var i = 0; i < this.length; i++) 85 result.push(this[i]) 86 return(result) 87 } 88 return staticFunction.apply(this, [this].concat(toArray.apply(arguments))) 89 } 90 } 91 92 function validateCallback(callback) { 93 if (!jQuery.isFunction(callback)) 94 throw("callback needs to be a function, it was: " + callback); 95 } 96 97 function negate(f) { 98 return function() { 99 return !f.apply(this, arguments) 100 } 101 } 102 })( jQuery );