Skip to content

Instantly share code, notes, and snippets.

@icambron
Created April 5, 2016 00:40
Show Gist options
  • Save icambron/edfa938aa01c46c5e9377088fd34b5fb to your computer and use it in GitHub Desktop.
Save icambron/edfa938aa01c46c5e9377088fd34b5fb to your computer and use it in GitHub Desktop.
Fun with proxies
function dateUTC(date, offset = 0){
let d = new Date(date),
adjust = (dir, item) => offset == 0 ? item : new Date(+item + offset * 60 * 1000 * -dir),
shift = (v) => {s = adjust(1, d);
return v;},
unshift = (v) => {d = adjust(-1, s);
return v;},
rewrites = {
getFullYear: () => s.getUTCFullYear(),
getMonth: () => s.getUTCMonth(),
getDate: () => s.getUTCDate(),
getHours: () => s.getUTCHours(),
getMinutes: () => s.getUTCMinutes(),
getSeconds: () => s.getUTCSeconds(),
getMilliseconds: () => s.getUTCMilliseconds(),
getTimezoneOffset: () => offset == 0 ? 0 : offset,
setFullYear: (y) => unshift(s.setUTCFullYear(y)),
setDate: (d) => unshift(s.setUTCDate(d)),
setMonth: (m) => unshift(s.setUTCMonth(m)),
setHours: (h) => unshift(s.setUTCHours(h)),
setMinutes: (m) => unshift(s.setUTCMinutes(m)),
setSeconds: (s) => unshift(s.setUTCSeconds(s)),
setMilliseconds: (ms) => unshift(s.setUTCMilliseconds(ms)),
valueOf: () => d.valueOf()
};
shift();
return new Proxy(d, {
get(target, key, receiver){
return function (...args) {
if (rewrites[key]) {
return rewrites[key].apply(this, args);
}
else {
return target[key].apply(d, args);
}
};
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment