Created
January 17, 2022 15:24
-
-
Save honzabrecka/d0ccfaef7cb20af5094d84d2fee11895 to your computer and use it in GitHub Desktop.
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
const metaProp = Symbol.for("meta"); | |
function withMeta(m, x) { | |
Object.defineProperty(x, metaProp, { | |
value: m, | |
writable: true, | |
configurable: true, | |
enumerable: false, | |
}); | |
return x; | |
} | |
function meta(x) { | |
return x[metaProp]; | |
} | |
function alterMeta(x, f) { | |
x[metaProp] = f(x[metaProp]); | |
return x; | |
} | |
function resetMeta(x) { | |
delete x[metaProp]; | |
return x; | |
} | |
const a = { foo: "bar" }; | |
const b = withMeta({ version: 1 }, a); | |
console.log(a, b, a === b); | |
console.log( | |
JSON.stringify(a), | |
JSON.stringify(b), | |
JSON.stringify(a) === JSON.stringify(b) | |
); | |
console.log(Object.entries(a), Object.entries(b)); | |
console.log(meta(a), meta(b)); | |
const c = alterMeta(a, ({ version }) => ({ version: version + 1 })); | |
console.log(meta(a), a, meta(c), c); | |
const d = resetMeta(a); | |
console.log(meta(a), a, meta(d), d); |
Author
honzabrecka
commented
Jan 17, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment