Skip to content

Instantly share code, notes, and snippets.

@rndme
Created April 17, 2024 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rndme/0d6ca238edb8e364ed402de0fdf287b1 to your computer and use it in GitHub Desktop.
Save rndme/0d6ca238edb8e364ed402de0fdf287b1 to your computer and use it in GitHub Desktop.
creates real genuine Arrays that are immutable but "polyfill" mutating methods
// ccby@dandavis
function ImmutableArray(){
function odp(k,v){ Object.defineProperty(r,k,{value:v}); }
let r = [...arguments];
if(r.length===1 && Array.isArray(r[0])) r = r[0];
odp("push", function(){return ImmutableArray(r.concat(...arguments));});
odp("unshift", function(){return ImmutableArray(r.toSpliced(0,0,...arguments));});
odp("splice", x=>ImmutableArray(r.toSpliced()));
odp("sort", x=>ImmutableArray(r.toSorted()));
odp("reverse", x=>ImmutableArray(r.toReversed()));
odp("fill", function(){return ImmutableArray(r.slice().fill(...arguments));});
odp("copyWithin", function(){return ImmutableArray(r.slice().copyWithin(...arguments));});
odp("pop", x=>r.slice(-1)[0]);
odp("shift", x=>r[0]);
odp("length", r.length);
Object.freeze(r);
return r;
}// end ImmutableArray()
let r = new ImmutableArray([11,22,33]);
r.push(55).fill(66,1,3); // == [11,66,66,55]
r; // == [11,22,33]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment