Functional Prog

Functional Programming

Functional programming is a paradigm that encourages developers to write code that does not have mutable data and is stateless. By definition, it tells us to treat our programs as mathematical functions which always produce identical results when the same values are passed into them. Because we know what the output of the function will be, this approach reduces the amount of surprises in the code.

Imperative Code

const getTotalFortuneOfTenRichest = (richPeople) => {
  richPeople.sort((first, second) => first.money - second.money);

  let sum = 0;

  for (let i = 0; i < richPeople.length; i++) {
    sum += richPeople[i].money;

    if (i >= 10) {
      return sum;
    }
  }
};

Declarative Code

const getTotalFortuneOfTenRichest = (richPeople) =>
  [...richPeople]
    .sort((first, second) => first.money - second.money)
    .slice(0, 10)
    .reduce((total, person) => total + person.money, 0);