Skip to content

Instantly share code, notes, and snippets.

@Atulin
Created March 18, 2025 16:37
Show Gist options
  • Select an option

  • Save Atulin/67dbcc9941cbec43b4529b74c45daccb to your computer and use it in GitHub Desktop.

Select an option

Save Atulin/67dbcc9941cbec43b4529b74c45daccb to your computer and use it in GitHub Desktop.
Experimenting with low weight code to manipulate Javascript dates
type Props = "FullYear"| "Month"| "Date"| "Hours"| "Minutes"| "Seconds"| "Milliseconds";
type Getter = `get${Props}`;
type Setter = `set${Props}`;
type DeltaDate = Partial<Record<Lowercase<Props>, number | undefined>>;
const getProp = (obj: DeltaDate, prop: Props) => obj[prop.toLowerCase() as Lowercase<Props>] ?? 0
export const mutateDate = (date: Date, delta: DeltaDate) => {
for (const p of Object.keys(delta) as Props[]) {
date[`set${p}` as Setter](date[`get${p}` as Getter]() + getProp(delta, p));
}
}
export const changeDate = (date: Date, delta: DeltaDate) => {
const d = new Date(date);
for (const p of Object.keys(delta) as Props[]) {
d[`set${p}` as Setter](date[`get${p}` as Getter]() + getProp(delta, p));
}
return d;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment