Skip to content

Instantly share code, notes, and snippets.

@KooiInc
Created March 3, 2023 15:46
Show Gist options
  • Save KooiInc/9fe9ee8e45f3be4b11c00fbbc8c42779 to your computer and use it in GitHub Desktop.
Save KooiInc/9fe9ee8e45f3be4b11c00fbbc8c42779 to your computer and use it in GitHub Desktop.
A small Date (proxy) helper
function dateProxyFactory() {
const props = {
year: (d, v) => v && d.setFullYear(v) || d.getFullYear(),
month: (d, v) => v && d.setMonth(v - 1) || d.getMonth() + 1,
date: (d, v) => v && d.setDate(v) || d.getDate(),
hours: (d, v) => v && d.setHours(v) || d.getHours(),
minutes: (d, v) => v && d.setMinutes(v) || d.getMinutes(),
seconds: (d, v) => v && d.setSeconds(v) || d.getSeconds(),
ms: (d, v) => v && d.setMilliseconds(v) || d.getMilliseconds(),
all: d => [ d.getFullYear(), d.getMonth(), d.getDate(),
d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds() ],
dt: d => d,
local: d => d.toLocaleString()
};
return date => {
const dProxy = {
get: (obj, name) => props[name]?.(obj) ?? obj[name],
set: ( obj, name, value) => props[name]?.(obj, value),
};
return new Proxy(date, dProxy);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment