Created
December 17, 2020 01:08
-
-
Save p7g/908ee893b655bde1a33934476da6ec09 to your computer and use it in GitHub Desktop.
Simple Python collections.ChainMap-esque construct in JavaScript
This file contains hidden or 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
// 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