DEV Community

loading...

Discussion on: Functional Programming Principles in Javascript

Collapse
johnboy5358 profile image
John

Hi TK,
I really like the fp style in JS, but how can I (or you) justify it, if, when I refer to your last shoppingCart example...

function imperativeGetTotalAmount(shoppingCart) {
  let amnt = 0
  for(let o of shoppingCart) amnt += o.type==='books' && o.amount
  return amnt
}

console.log(imperativeGetTotalAmount(shoppingCart))
// => 70

imperativeGetTotalAmount, also gives me the correct value and will be much quicker to execute, particularly when the "shoppingCart" array length is length 10,000 or greater? Additionally, the code length of imperativeGetTotalAmount is shorter.

Once again, I must reiterate, I am a huge fp fan and I am playing devil's advocate here in posing this question, but I feel that one must be able to defend a particular style,(oop, imperative, fp), if it is to be accepted by the community in general.

Thanks for your post and it's huge list of useful resources.

  • STOP PRESS ...

This solution returns an amazingly fast execution time for 100,000 generated items of approx. 2.5ms


function getTotalAmount(shoppingCart) {
  return shoppingCart.reduce((acc, obj) => {
    return obj.type === 'books'
    ? acc + obj.amount
    : acc
  },0)
}

or, alternatively ...


const getTotalAmount = (shoppingCart) =>
  shoppingCart.reduce((acc, obj) =>
    obj.type === 'books'
    ? acc + obj.amount
    : acc, 0)

visit runkit link