Last active
August 1, 2024 10:30
-
-
Save sirlancelot/5f1922ef01e8006ea9dda6504fc06b8e to your computer and use it in GitHub Desktop.
Create a "frozen" date object
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
// Date objects frozen with `Object.freeze()` are still mutable due to the way | |
// JavaScript stores the internal value. You can create a truly immutable, | |
// "frozen" date object by wrapping it in a proxy which ignores set* functions. | |
const noop = () => {} | |
const dateProxyHandler = { | |
get(target, prop, receiver) { | |
if (prop === Symbol.toStringTag) return "Date" | |
if (typeof prop === "string" && prop.startsWith("set")) return noop | |
const value = Reflect.get(target, prop, receiver) | |
return typeof value === "function" && prop !== "constructor" | |
? value.bind(target) | |
: value | |
}, | |
} | |
function freeze(value) { | |
return value instanceof Date | |
? new Proxy(Object.freeze(new Date(Number(value))), dateProxyHandler) | |
: Object.freeze(value) | |
} | |
const frozenDate = freeze(new Date()) | |
frozenDate.setHours(0) // noop | |
frozenDate.getHours() // works :) | |
JSON.stringify(frozenDate) // works :) | |
const copiedDate = new Date(Number(frozenDate)) // works :) | |
Object.prototype.toString.call(frozenDate) // "[object Date]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment