0

please tell me how to make this function smaller how can i combine map reduse and if check in one function

const items = [
  { prise: 40 },
  { prise: -120 },
  { prise: "505" },
  { prise: 350 },
];

const isType = (item) => {
  if (typeof item.prise === "number" && item.prise > 0) {
    return item.prise;
  }
  return 0;
};

const sum = items.map((key) => {
  return isType(key);
});

const total = sum.reduce((acc, item) => acc + item);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 3
    I’m voting to close this question because it's about refactoring working code, so it belongs on https://codereview.stackexchange.com – Rory McCrossan Oct 11 '22 at 11:19
  • 1
    Move the `isType` call into the reducer directly? `const total = items.reduce((acc, item) => acc + isType(item), 0);` – Terry Oct 11 '22 at 11:19
  • `sum.map(isType).reduce((acc, item) => acc + item)` but transducers might be more relevant. See: [Transducer flatten and uniq](https://stackoverflow.com/q/52008364) and [How to chain map and filter functions in the correct order](https://stackoverflow.com/q/44198833) for examples. – VLAZ Oct 11 '22 at 11:19
  • 1
    btw, a function which starts with `is...` is ment to return a boolean value. – Nina Scholz Oct 11 '22 at 11:20
  • I know English it not everyone's native tongue here, but `prise` did you mean either `price` or `prize`.. – Keith Oct 11 '22 at 11:26

2 Answers2

1

You can achieve it with a single function like so:

const total = items.reduce((acc, curr) => acc + isType(curr), 0);

const items = [{
    prise: 40
  },
  {
    prise: -120
  },
  {
    prise: "505"
  },
  {
    prise: 350
  },
];

const isType = (item) => {
  if (typeof item.prise === "number" && item.prise > 0) {
    return item.prise;
  }
  return 0;
};

const total = items.reduce((acc, curr) => acc + isType(curr), 0);


console.log(total);
Joel
  • 5,732
  • 4
  • 37
  • 65
0

const items = [
  { prise: 40 },
  { prise: -120 },
  { prise: "505" },
  { prise: 350 },
];

const isType = (item) => {
  if (typeof item.prise === "number" && item.prise > 0) {
    return item.prise;
  }
  return 0;
};

const total = items.reduce(function (item, currVal) {
    return item + isType(currVal);
}, 0);

console.log(total)
Ahmad Faraz
  • 1,371
  • 1
  • 4
  • 11