Skip to content

Instantly share code, notes, and snippets.

@p7g
Created December 17, 2020 01:08
Show Gist options
  • Save p7g/908ee893b655bde1a33934476da6ec09 to your computer and use it in GitHub Desktop.
Save p7g/908ee893b655bde1a33934476da6ec09 to your computer and use it in GitHub Desktop.
Simple Python collections.ChainMap-esque construct in JavaScript
// The behaviour of Python's collections.ChainMap is the same as prototypal
// inheritance[1] in JavaScript:
//
// - Accessing a property of an object will traverse the prototype chain until
// the property is found (or until the end of the chain); and
// - Assigning to a property will only mutate the first object in the prototype
// chain (the object on which the property is being accessed).
//
// Thanks to this, we can implement something along the lines of Python's
// collections.ChainMap quite trivially.
//
// [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
export default function ChainMap(...maps) {
if (!maps.length)
return Object.create(null);
const [m, ...ms] = maps;
return Object.setPrototypeOf(m, chainmap(...ms));
}
export function newChild(m) {
return Object.create(m);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment