Last active
March 16, 2023 01:50
-
-
Save ayrusme/e57add78329fdae2c06940e409efdb8e to your computer and use it in GitHub Desktop.
Alternate way to detect changes to any value in an Object
This file contains 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
let initialObject = { | |
goingToChange: true, | |
firstKey: 'firstKey', | |
secondKey: 'secondKey', | |
thirdKey: 'thirdKey' | |
}; | |
const changedProperties = []; | |
// define a setter to push to an array if a value inside object changes | |
const handler = { | |
set(target, property, value) { | |
if (value != target[property]) { | |
changedProperties.push(property); | |
} | |
target[property] = value; | |
return true; | |
}, | |
get: function (target, property) { | |
return target[property]; | |
} | |
} | |
// assign the handler to the object via proxy | |
const proxyObject = new Proxy(initialObject, handler); | |
proxyObject.goingToChange = false; | |
// see the key present inside this array since value was changed | |
console.log(changedProperties); | |
// INFO: proxy can also prevent setting any other dataType to the key than the existing type | |
// proxies are awesome | |
// MORE reading at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alternatively, can use a Set to ensure O(1) complexity for lookups