Skip to content

Instantly share code, notes, and snippets.

@zettadam
Last active October 27, 2024 15:42
Show Gist options
  • Select an option

  • Save zettadam/b6a5a897f0f8af1aa1e87449e91f520a to your computer and use it in GitHub Desktop.

Select an option

Save zettadam/b6a5a897f0f8af1aa1e87449e91f520a to your computer and use it in GitHub Desktop.
Partition a JS array of dated items into 'previous week', 'previous month', 'previous quarter', 'previous year' and then each consequtive year.
/**
* Partitions given array with date field (published) into period arrays.
*
* @param {Array.<Object>} items
* @returns Map<string | number, Array.<Object>>
*/
export function groupByPublishedPeriod(items) {
const o = new Map() // since key insertion order may be important
o.set('week', [])
o.set('month', [])
o.set('quarter', [])
o.set('year', [])
const n = new Date()
const w = subtractDays(n, 7)
const m = subtractMonths(n, 1)
const q = subtractMonths(n, 3)
const y = subtractMonths(n, 12)
items.forEach((i) => {
const p = new Date(item.published)
if (p >= w) o.get('week').push(i)
else if (p >= m) o.get('month').push(i)
else if (p >= q) o.get('quarter').push(i)
else if (p >= y) o.get('year').push(i)
else {
const Y = p.getFullYear()
if (!o.has(Y)) o.set(y, [])
o.get(Y).push(i)
}
})
return o
}
/**
* Subtracts a number of days from a date.
*
* @param {Date} date
* @param {Number} days
* @returns Date
*/
function subtractDays(date: Date, days: number): Date {
const d = new Date(date)
d.setDate(d.getDate() - days)
return d
}
/**
* Subtracts a number of months from a date.
*
* @param {Date} date
* @param {Number} months
* @returns Date
*/
function subtractMonths(date: Date, months: number): Date {
const d = new Date(date)
d.setMonth(d.getMonth() - months)
return d
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment