Hi, Reddit. I am these kind of ppl who can do two thing forever:Watch fireDo refactoringand I got interesting task few hours ago:Chunk transactions by week and calculate their amount sum (for diagram).Transaction model:Transaction { date: Date, value: {usd: number} } And I have to calculate total amount per week taking 8 last weeksApi result: https://ift.tt/2mirpPm stack: mongo (mongoose), moment.js (don't like it cuz mutable :/)here is mine solution:Pastebin verisonconst weeksTransactionsStats = transactionKind => async (req, res) => { // weeks to find from now const statsWeeksCount = 8 const weekKind = 'isoWeek' // calculate statsWeeksCount from now to monday const cutoffMoment = moment().endOf(weekKind).subtract(statsWeeksCount, 'weeks') // filter transactions, these created later than cutoff const transactions = await Transaction .find({kind: transactionKind, date: {$gt: cutoffMoment.valueOf()}}) .sort({date: 1}) // stats initialization let stats = (function initializeStats(){ let edgeDateMoment = cutoffMoment.clone() return new Array(statsWeeksCount).fill().map(((_, index) => ({ totalAmount: 0, beginDate: edgeDateMoment.format(), endDate: edgeDateMoment.add(1, 'weeks').format() }))) })(); // chunk transactions by weeks and calcalate stats (function calculateStats(){ let edgeDateMoment = cutoffMoment.clone().add(1, 'weeks') let index = 0 // stats array index transactions.forEach(transaction => { if (!moment(transaction.date).isBefore(edgeDateMoment)){ // incrementing to next week index += 1 edgeDateMoment.add(1, 'weeks') } stats[index].totalAmount += transaction.value.usd console.log(transaction.date) }) })(); res.status(200).json({success: true, data: stats}) } I really want to hear your feedback guys. I will be appreciated
Submitted July 14, 2018 at 12:09AM by poloabuser
No comments:
Post a Comment