Skip to content

Instantly share code, notes, and snippets.

@honzabrecka
Created January 17, 2022 15:24
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 honzabrecka/d0ccfaef7cb20af5094d84d2fee11895 to your computer and use it in GitHub Desktop.
Save honzabrecka/d0ccfaef7cb20af5094d84d2fee11895 to your computer and use it in GitHub Desktop.
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);
@honzabrecka
Copy link
Author

$ node meta.js
{ foo: 'bar' } { foo: 'bar' } true
{"foo":"bar"} {"foo":"bar"} true
[ [ 'foo', 'bar' ] ] [ [ 'foo', 'bar' ] ]
{ version: 1 } { version: 1 }
{ version: 2 } { foo: 'bar' } { version: 2 } { foo: 'bar' }
undefined { foo: 'bar' } undefined { foo: 'bar' }

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