let shoppingCart = [
{ productTitle: "Functional Programming", type: "books", amount: 10 },
{ productTitle: "Kindle", type: "eletronics", amount: 30 },
{ productTitle: "Shoes", type: "fashion", amount: 20 },
{ productTitle: "Clean Code", type: "books", amount: 60 }
]
function getTotalAmount(shoppingCart) {
return shoppingCart.reduce((acc, obj) => {
return obj.type === 'books'
? acc + obj.amount
: acc
},0)
}
function imperativeGetTotalAmount(shoppingCart) {
let rTot = 0
for(let item of shoppingCart) rTot += item.type==='books' && item.amount
return rTot
}
console.log(getTotalAmount(shoppingCart))
console.log(imperativeGetTotalAmount(shoppingCart))
function genTestAry(numElements) {
let A = [], i=0, prod=["books", "eletronics", "fashion", "diy", "health"]
while (i<numElements) {
A.push({productTitle:'', ['type']: prod[~~(i%5)], amount: 10})
i++
}
return A
}
// Generate
const sCart = genTestAry(100000)
console.log('sCart length',sCart.length)
console.time('getTotalAmount')
console.log(getTotalAmount(sCart))
console.timeEnd('getTotalAmount')
console.time('imperativeGetTotalAmount')
console.log(imperativeGetTotalAmount(sCart))
console.timeEnd('imperativeGetTotalAmount')