Created
December 13, 2017 13:18
-
-
Save shqld/ba16551a67544ca6893149e5930f92b5 to your computer and use it in GitHub Desktop.
Abstract dictionaries in ES2015 with immutability and method chaining
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
const repository = Symbol('repository') | |
class Dict { | |
constructor(props) { | |
if (typeof props !== 'object') { | |
throw new Error( | |
`Props must be an object, you passed ${typeof props} ${props}.` | |
) | |
} | |
Object.freeze(props) | |
Object.defineProperty(this, repository, { | |
value: props, | |
}) | |
Object.freeze(this) | |
} | |
merge(props) { | |
return new Dict({ | |
...this[repository], | |
...props, | |
}) | |
} | |
set(key, value) { | |
return new Dict({ | |
...this[repository], | |
[key]: value, | |
}) | |
} | |
get(key) { | |
return this[repository][key] | |
} | |
} | |
module.exports = Dict |
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
const weakMap = new WeakMap() | |
class Dict { | |
constructor(props) { | |
if (typeof props !== 'object') { | |
throw new Error( | |
`Props must be an object, you passed ${typeof props} ${props}.` | |
) | |
} | |
weakMap.set(this, props) | |
Object.freeze(this) | |
} | |
set(key, value) { | |
return new Dict({ | |
...weakMap.get(this), | |
[key]: value, | |
}) | |
} | |
merge(props) { | |
return new Dict({ | |
...weakMap.get(this), | |
...props, | |
}) | |
} | |
get(key) { | |
return weakMap.get(this)[key] | |
} | |
} | |
module.exports = Dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment