Created
September 9, 2015 09:53
-
-
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.
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
| /** | |
| * 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