Skip to content

Instantly share code, notes, and snippets.

@oriSomething
Created February 26, 2018 13:11
Show Gist options
  • Save oriSomething/88650e437c10ca97d9575aaa01fef3b4 to your computer and use it in GitHub Desktop.
Save oriSomething/88650e437c10ca97d9575aaa01fef3b4 to your computer and use it in GitHub Desktop.
Make Immutable.List useful for Array consume functions without immediate cast to Array
function asArray(target) {
if (!Immutable.List.isList(target)) {
throw new TypeError("target is not Immutable.List");
}
return new Proxy(new Array(target.size), {
get(__, key, receiver) {
if (typeof key !== "symbol") {
const index = parseInt(key, 10);
if (Number.isFinite(index) && index >= 0) {
return target.get(key);
}
switch (key) {
case "fill":
case "pop":
case "push":
case "shift":
case "sort":
case "splice":
case "unshift":
throw new Error(`Cannot mutate Immutable.List with operation "${key}"`);
case "length":
return target.size;
case "constructor":
return Array;
case "concat":
case "filter":
case "map":
case "prototype":
case "slice":
case "toString":
return target.toArray()[key];
}
}
return Reflect.get(target, key, receiver);
},
set() {
throw new Error("Cannot mutate Immutable.List by assignment");
},
deleteProperty() {
throw new Error("Cannot delete properties from Immutable.List");
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment