Skip to content

Instantly share code, notes, and snippets.

@ayrusme
Last active March 16, 2023 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayrusme/e57add78329fdae2c06940e409efdb8e to your computer and use it in GitHub Desktop.
Save ayrusme/e57add78329fdae2c06940e409efdb8e to your computer and use it in GitHub Desktop.
Alternate way to detect changes to any value in an Object
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
@ayrusme
Copy link
Author

ayrusme commented Aug 16, 2022

alternatively, can use a Set to ensure O(1) complexity for lookups

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment