Skip to content

Instantly share code, notes, and snippets.

@joar
Created September 9, 2015 09:53
Show Gist options
  • Select an option

  • Save joar/aa8b04ed8e8af91a7ac7 to your computer and use it in GitHub Desktop.

Select an option

Save joar/aa8b04ed8e8af91a7ac7 to your computer and use it in GitHub Desktop.
Key -> value mapping that keeps track of if any value has been updated.
/**
* Key -> value mapping that keeps track of if any value has been updated.
*/
class TrackingMap {
constructor(initial={}) {
this.updated = true
for (let field in initial) {
if (field.charAt(0) == '_') {
throw new Error('You may not start field names with an' +
' underscore.')
}
if (field == 'updated') {
throw new Error('"updated" is a reserved field name')
}
let internalField = `_${field}`
let initialValue = initial[field]
this[internalField] = initialValue
Object.defineProperty(this, field, {
get: () => {
return this[internalField]
},
set: (value) => {
let before = this[internalField]
if (before !== value) {
this.updated = true
}
this[internalField] = value
},
configurable: true,
enumerable: true
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment