Javascript Arrays — Funciones inmutables

Lista de las funciones inmutables de Javascript para trabajar con arrays

Image for post
Image for post
Funciones inmutables

Inmutable Push

function immutablePush(arr, newEntry){
return [ ...arr, newEntry ]
}

Inmutable Pop

function immutablePop(arr){
return arr.slice(0, -1)
}

Inmutable Unshift

function immutableUnshift(arr, newEntry){
return [ newEntry, ...arr ]
}

Sort

function immutableSort(arr, compareFunction) {
return [ ...arr ].sort(compareFunction)
}
// o bien...function immutableSort(arr, compareFunction) {
return arr.slice().sort(compareFunction)
}

Reverse

function immutableSort(arr, compareFunction) {
return [ ...arr ].reverse()
}
// o bien...function immutableSort(arr, compareFunction) {
return arr.slice().reverse()
}

Splice

// ES5function immutableSplice(arr, start, deleteCount) {
var _len = arguments.length
var items = Array(_len > 3 ? _len - 3 : 0)
for (var _key = 3; _key < _len; _key++) {
items[_key - 3] = arguments[_key];
}
return [].concat(arr.slice(0, start), items, arr.slice(start + deleteCount))
}
// ES6function immutableSplice(arr, start, deleteCount, ...items) {
return [ ...arr.slice(0, start), ...items, ...arr.slice(start + deleteCount) ]
}

Delete

function immutableDelete (arr, index) {
return arr.slice(0,index).concat(arr.slice(index+1))
}

¿Quieres recibir más artículos como este?

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store