Created
April 17, 2024 07:35
-
-
Save rndme/0d6ca238edb8e364ed402de0fdf287b1 to your computer and use it in GitHub Desktop.
creates real genuine Arrays that are immutable but "polyfill" mutating methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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