Skip to content

Instantly share code, notes, and snippets.

@sirlancelot
Last active April 19, 2021 18:16
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 sirlancelot/5f1922ef01e8006ea9dda6504fc06b8e to your computer and use it in GitHub Desktop.
Save sirlancelot/5f1922ef01e8006ea9dda6504fc06b8e to your computer and use it in GitHub Desktop.
Create a "frozen" date object
// 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