/** * Class : JSL.array * Handles all the array related functions. * Argument: arr - The array on which the operation must be done. */ (function() { /// Constructor function _array_init(arr) { this.array = arr; //Get all the array function in the 'this' element itself - stuff like map(), each for(var i in this.array) { this[i] = this.array[i]; } this.length = arr.length; return this; } _array_init.prototype = { /** * This function will loop thru the array and call the given function for each element. * The values returned by the user defined function will be used to create a new * array/object that is returned by the function at the end. 3 arguments will be passed to * the user defined function - * - current_item - The value of the current element * - index - The index we are currently at * - full_array - The entire array * - user_args - The data provided by the user, if any. * * Argument: * func - The user function. * user_args - Custom data passed into the function [OPTIONAL] * Example: *
var result = JSL.array([4,10,65]).map(function(current_item) {
* return current_item+1;
* });
* Result will be [5, 11, 66]
*
* var result = JSL.array([4,10,65]).map(function(current_item, x) {
* return current_item + x;
* }, 5);
* Result will be [9, 15, 70] - 5, the second argument of the map function is passed into the 1st argument function.
*/
"map" : function() {
var func = arguments[0];
func = JSL._makeFunc(func,"ele,i,all");
var user_args = JSL._getUserArgs(arguments);
var is_array = this.isList();
var result = (is_array) ? [] : {};
function _callUserFunction(index, user_args, result) {
var return_value = func.apply(this, [this.array[index], index, this.array].concat(user_args));
if(return_value != undefined) {
if(is_array) result.push(return_value);
else result[index] = return_value;
}
return result;
}
// I use 2 differnt methods of accessing the array elements based on what kind of data it is - yeah, I hate doing this.
// So why am I doing this? To get the small performance boost promised in http://batiste.dosimple.ch/blog/posts/2007-02-27-1/javascript-loop-benchmark.html
if(is_array) { //This part is for the lists
array_length = this.array.length;
for(var index=0; index