Last active
February 6, 2020 12:51
-
-
Save suspectpart/2cfbb0999695c93cb0e3627ed8b248f4 to your computer and use it in GitHub Desktop.
SectionGrid Spike
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Group a list of item by key. | |
* @param list | |
* @param keyGetter | |
* @returns {Map<any, any>} | |
*/ | |
function groupBy(list, keyGetter) { | |
const map = new Map(); | |
for (const item of list) { | |
const key = keyGetter(item); | |
const bucket = map.get(key) || []; | |
map.set(key, [... bucket, item]) | |
} | |
return map; | |
} | |
/** | |
* Model for a single order | |
*/ | |
class Order { | |
_date; | |
_name; | |
constructor(name, date) { | |
this._date = date; | |
this._name = name; | |
} | |
date() { | |
return this._date; | |
} | |
year() { | |
return this._date.getFullYear(); | |
} | |
[Symbol.toPrimitive](hint) { | |
return hint === "number" ? +this.date() : this._name; | |
} | |
compareTo(other) { | |
return this > other ? 1 : -1; | |
} | |
} | |
/** | |
* Model that manages a list of orders | |
*/ | |
class Orders { | |
_orders; | |
constructor(...orders) { | |
this._orders = [...orders]; | |
this._orders.sort((o1, o2) => o1.compareTo(o2)); | |
} | |
groupedByYear() { | |
return new groupBy([...this], order => order.year()); | |
} | |
* [Symbol.iterator]() { | |
for (let order of this._orders) { | |
yield order; | |
} | |
} | |
} | |
const orders = new Orders( | |
new Order("ord-6789", new Date(2019, 1, 1)), | |
new Order("ord-9987", new Date(2016, 6, 7)), | |
new Order("ord-1345", new Date(2016, 6, 6)), | |
new Order("ord-1333", new Date(2019, 5, 3)), | |
new Order("ord-4121", new Date(2017, 10, 27)), | |
new Order("ord-7865", new Date(2019, 12, 1)), | |
new Order("ord-5232", new Date(2019, 7, 6)), | |
new Order("ord-3331", new Date(2008, 3, 29)), | |
); | |
// Orders are iterable | |
for (let order of orders) { | |
console.log(order); | |
} | |
// Orders allow for grouping | |
console.log(orders.groupedByYear()); | |
/** | |
* Create a component that knows how to render a map: | |
* | |
* <SectionGrid items={orders.groupedByYear()} renderItemsAs={OrderCard} /> | |
* | |
* OR | |
* | |
* <OrdersGrid orders={orders.groupedByYear()} /> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment