Skip to content

Instantly share code, notes, and snippets.

@yckart
Last active August 29, 2015 14:12
Show Gist options
  • Save yckart/c85978f284a3a5175347 to your computer and use it in GitHub Desktop.
Save yckart/c85978f284a3a5175347 to your computer and use it in GitHub Desktop.
Unchanging Array Functions

I had the need for some simplicity, to work with methods like push, pop, shift, unshift from Arrays prototype, that do not change itself.

Concept

The basic concept would look like something like this. I just implemented some basic methods to illustrate my thoughts. However, there are more possibilities. Read the note below.

Array#pop

array = array.slice(0, -1);

Array#shift

array = array.slice(1);

Array#push

array = array.concat(1337);

Array#unshift

array = [0].concat(array);

I have wrapped/aliased these methods in some simple functions (see index.js below):

var array = [1, 2, 3];
array = push(array, 4);    // => [1, 2, 3, 4]
array = pop(array);        // => [1, 2, 3]
array = unshift(array, 0); // => [0, 1, 2, 3]
array = shift(array);      // => [1, 2, 3]

Possibilities

Whoops, nothing here!

Why that?

...talking about the possiblities about protected array manipulation, really?!

function pop(array) { return array.slice(0, -1); }
function shift(array) { return array.slice(1); }
function push(array, value) { return array.concat(value); }
function unshift(array, value) { return [value].concat(array); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment