Normalizar métodos de matriz y valores de retorno.
¿Hay alguna biblioteca de Arrays de JavaScript que normalice los valores de retorno de Array y las mutaciones? Creo que la API de la matriz de JavaScript es muy inconsistente.
Algunos métodos mutan la matriz:
var A = [0,1,2];
A.splice(0,1); // reduces A and returns a new array containing the deleted elements
Algunos no
A.slice(0,1); // leaves A untouched and returns a new array
Algunos devuelven una referencia a la matriz mutada:
A = A.reverse().reverse(); // reverses and then reverses back
Algunos simplemente vuelven sin definir:
B = A.forEach(function(){});
Lo que me gustaría es mutar siempre la matriz y devolver siempre la misma matriz, para que pueda tener algún tipo de coherencia y también poder encadenar. Por ejemplo:
A.slice(0,1).reverse().forEach(function(){}).concat(['a','b']);
Probé algunos fragmentos simples como:
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();
Esto funciona bien para la mayoría de los métodos de mutación, pero hay problemas. Por ejemplo, necesito escribir prototipos personalizados para cada método que no mute la matriz original.
Entonces, como siempre, mientras hacía esto, pensaba que tal vez esto ya se había hecho antes. ¿Hay bibliotecas de matriz ligera que ya hacen esto? Sería bueno si la biblioteca también agrega shims para los nuevos métodos de JavaScript 1.6 para navegadores más antiguos.