Skip to content

Instantly share code, notes, and snippets.

@shqld
Created December 13, 2017 13:18
Show Gist options
  • Save shqld/ba16551a67544ca6893149e5930f92b5 to your computer and use it in GitHub Desktop.
Save shqld/ba16551a67544ca6893149e5930f92b5 to your computer and use it in GitHub Desktop.
Abstract dictionaries in ES2015 with immutability and method chaining
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
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