简体   繁体   中英

Combine a Reduce and Map Data Structure in Javascript?

I am trying to use the reduce pattern on a Javascript Array of objects. But, instead of doing this in a single reducer, I want to be able to use a different reducer based on a condition set for each of the items in the array. So, it would look like the following.

const FOO_MAP = new Map([
  ["Foo1", Bar1],
  ["Foo2", Bar2]]
);

function calcTotal(values) {
  if(values == null) return 0;
  return values.reduce(FOO_MAP.get(value.field));
}

function Bar1(previous, curr){...}
function Bar2(previous, curr){...}

Is this possible? Thanks!

您似乎在寻找

values.reduce((acc, el, i) => FOO_MAP.get(el.field)(acc, el, i), 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM