Question

Is there any JavaScript Array library that normalizes the Array return values and mutations? I think the JavaScript Array API is very inconsistent.

Some methods mutate the array:

var A = [0,1,2];
A.splice(0,1); // reduces A and returns a new array containing the deleted elements

Some don’t:

A.slice(0,1); // leaves A untouched and returns a new array

Some return a reference to the mutated array:

A = A.reverse().reverse(); // reverses and then reverses back

Some just return undefined:

B = A.forEach(function(){});

What I would like is to always mutate the array and always return the same array, so I can have some kind of consistency and also be able to chain. For example:

A.slice(0,1).reverse().forEach(function(){}).concat(['a','b']);

I tried some simple snippets like:

var superArray = function() {
    this.length = 0;
}

superArray.prototype = {
    constructor: superArray,

    // custom mass-push method
    add: function(arr) {
        return this.push.apply(this, arr);
    }
}

// native mutations
'join pop push reverse shift sort splice unshift map forEach'.split(' ').forEach(function(name) {
    superArray.prototype[name] = (function(name) {
        return function() {
            Array.prototype[name].apply(this, arguments);
            // always return this for chaining
            return this;
        };
    }(name));
});

// try it
var a = new superArray();
a.push(3).push(4).reverse();

This works fine for most mutation methods, but there are problems. For example I need to write custom prototypes for each method that does not mutate the original array.

So as always while I was doing this, I was thinking that maybe this has been done before? Are there any lightweight array libraries that do this already? It would be nice if the library also adds shims for new JavaScript 1.6 methods for older browsers.

Was it helpful?

Solution

I don't think it is really inconsistent. Yes, they might be a little confusing as JavaScript arrays do all the things for which other languages have separate structures (list, queue, stack, …), but their definition is quite consistent across languages. You can easily group them in those categories you already described:

  • list methods:
    • push/unshift return the length after adding elements
    • pop/shift return the requested element
    • you could define additional methods for getting first and last element, but they're seldom needed
  • splice is the all-purpose-tool for removing/replacing/inserting items in the middle of the list - it returns an array of the removed elements.
  • sort and reverse are the two standard in-place reordering methods.

All the other methods do not modify the original array:

  • slice to get subarrays by position, filter to get them by condition and concat to combine with others create and return new arrays
  • forEach just iterates the array and returns nothing
  • every/some test the items for a condition, indexOf and lastIndexOf search for items (by equality) - both return their results
  • reduce/reduceRight reduce the array items to a single value and return that. Special cases are:
    • map reduces to a new array - it is like forEach but returning the results
    • join and toString reduce to a string

These methods are enough for the most of our needs. We can do quite everything with them, and I don't know any libraries that add similar, but internally or result-wise different methods to them. Most data-handling libs (like Underscore) only make them cross-browser-safe (es5-shim) and provide additional utility methods.

What I would like is to always mutate the array and always return the same array, so I can have some kind of consistency and also be able to chain.

I'd say the JavaScript consistency is to alway return a new array when elements or length are modified. I guess this is because objects are reference values, and changing them would too often cause side effects in other scopes that reference the same array.

Chaining is still possible with that, you can use slice, concat, sort, reverse, filter and map together to create a new array in only one step. If you want to "modify" the array only, you can just reassign it to the array variable:

A = A.slice(0,1).reverse().concat(['a','b']);

Mutation methods have only one advantage to me: they are faster because they might be more memory-efficient (depends on the implementation and its garbage collection, of course). So lets implement some methods for those. As Array subclassing is neither possible nor useful, I will define them on the native prototype:

var ap = Array.prototype;
// the simple ones:
ap.each = function(){ ap.forEach.apply(this, arguments); return this; };
ap.prepend = function() { ap.unshift.apply(this, arguments); return this; };
ap.append = function() { ap.push.apply(this, arguments; return this; };
ap.reversed = function() { return ap.reverse.call(ap.slice.call(this)); };
ap.sorted = function() { return ap.sort.apply(ap.slice.call(this), arguments); };
// more complex:
ap.shorten = function(start, end) { // in-place slice
    if (Object(this) !== this) throw new TypeError();
    var len = this.length >>> 0;
    start = start >>> 0; // actually should do isFinite, then floor towards 0
    end = typeof end === 'undefined' ? len : end >>> 0; // again
    start = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
    end = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
    ap.splice.call(this, end, len);
    ap.splice.call(this, 0, start);
    return this;
};
ap.restrict = function(fun) { // in-place filter
    // while applying fun the array stays unmodified
    var res = ap.filter.apply(this, arguments);
    res.unshift(0, this.length >>> 0);
    ap.splice.apply(this, res);
    return this;
};
ap.transform = function(fun) { // in-place map
    if (Object(this) !== this || typeof fun !== 'function') throw new TypeError();
    var len = this.length >>> 0,
        thisArg = arguments[1];
    for (var i=0; i<len; i++)
        if (i in this)
            this[i] = fun.call(thisArg, this[i], i, this)
    return this;
};
// possibly more

Now you could do

A.shorten(0, 1).reverse().append('a', 'b');

OTHER TIPS

IMHO one of the best libraries is underscorejs http://underscorejs.org/

You probably shouldn't use a library just for this (it's a not-so-useful dependency to add to the project).

The 'standard' way to do is to call slice when you want to exec mutate operations. There is not problem to do this, since the JS engines are pretty good with temporary variables (since that's one of the key point of the javascript).

Ex. :

function reverseStringify( array ) {
    return array.slice( )
        .reverse( )
        .join( ' ' ); }

console.log( [ 'hello', 'world' ] );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top