Last active
December 26, 2019 18:28
-
-
Save mahmoudafer/fae91c90c3806e30bb460ba8ffc30c48 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const data = [ | |
{ | |
transactionId: "t-100", | |
userId: 123, | |
category: "appliances", | |
total: 22.4, | |
}, | |
{ | |
transactionId: "t-101", | |
userId: 123, | |
category: "electronics", | |
total: 120.8, | |
}, | |
{ | |
transactionId: "t-102", | |
userId: 122, | |
category: "appliances", | |
total: 280.4, | |
}, | |
{ | |
transactionId: "t-103", | |
userId: 122, | |
category: "electronics", | |
total: 0.4, | |
}, | |
{ | |
transactionId: "t-104", | |
userId: 121, | |
category: "appliances", | |
total: 1800, | |
}, | |
{ | |
transactionId: "t-105", | |
userId: 124, | |
category: "electronics", | |
total: 1222, | |
}, | |
]; | |
class transactionsUtils { | |
static highestTransactionId = (arr) => { | |
const reducer = (highestObj, currentObj) => highestObj = currentObj.total > highestObj.total ? currentObj : highestObj; | |
return arr.reduce(reducer, arr[0]).transactionId; | |
} | |
static _highestSumOfUnit = (arr, property) => { //helper function | |
const sums = {}; | |
arr.forEach(transaction => { | |
sums[transaction[property]] = sums[transaction[property]] == undefined ? transaction.total : sums[transaction[property]] + transaction.total; | |
}); | |
return Object.keys(sums).reduce((highestSum, current) => highestSum = sums[current] > sums[highestSum] ? current : highestSum, Object.keys(sums)[0]) | |
} | |
static highestSumOfTransactionsUser = (arr) => this._highestSumOfUnit(arr, 'userId') | |
static highestSalesCategory = (arr) => this._highestSumOfUnit(arr, 'category') | |
} | |
console.log(transactionsUtils.highestTransactionId(data)) | |
console.log(transactionsUtils.highestSumOfTransactionsUser(data)) | |
console.log(transactionsUtils.highestSalesCategory(data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment