Использование JS функции уменьшения, отображения или фильтрации - PullRequest
0 голосов
/ 04 августа 2020

Есть ли более эффективный способ добиться этого? Мой желаемый результат - создать новый массив из следующего объекта. Если supported === true, добавить id в массив. Итак, в нижеследующем объекте вывод должен быть ['CREDIT', 'DEBIT'].

 const object = {
   "cardOptions": [
   {
      "id": "CREDIT",
      "supported": true
   },
   {
      "id": "DEBIT",
      "supported": true
   }
  ]
 }

Вот что у меня есть сейчас.

 const cardTypes = object.reduce((filtered, cardType) => {
      if (cardType.id && cardType.supportedAtLocation) {
          filtered.push(cardType.id)
      }
      return filtered
 }, [])

1 Ответ

2 голосов
/ 04 августа 2020

Вы также можете использовать фильтр + карту следующим образом:

object.cardOptions
  .filter(option => option.supported)
  .map(cardOption => cardOption.id)

Профилирование этого бок о бок с помощью User Timing API , по крайней мере, на chrome, похоже, ваш Код reduce более эффективен (но на практике это, вероятно, не имеет значения, если у вас нет действительно большого набора данных).

Вот быстрая функция профилирования более высокого порядка, которую я часто использую:

// A function to run an input function several times and profile performance using the User Timing API on chrome
const profile = (func, times) => (...args) => {
    const functionName = func.name;
    const trackName = `${functionName}`;
    const startTag = `${trackName}_start`;
    window.performance.mark(startTag);
    let results;
    for (let i = 0; i < times; i = i + 1)
        results = func(...args);
    const endTag = `${trackName}_end`;
    window.performance.mark(endTag);
    window.performance.measure(trackName, startTag, endTag);
    return results;
};
const object = {
    cardOptions: [
        {
            id: 'CREDIT',
            supported: true,
        },
        {
            id: 'DEBIT',
            supported: true,
        },
    ],
};
const filterMap = () => {
    object.cardOptions
        .filter(option => option.supported)
        .map(cardOption => cardOption.id);
};
const reduce = () => {
    object.cardOptions.reduce((filtered, cardType) => {
        if (cardType.id && cardType.supported) {
            filtered.push(cardType.id);
        }
        return filtered;
    }, []);
};

profile(filterMap, 99999)();
profile(reduce, 99999)();

Результат измерения выглядит так:

window.performance.getEntriesByType('measure')

[
  {
    name: 'profileFilterMap',
    entryType: 'measure',
    startTime: 310637.6400000008,
    duration: 30.029999994440004, // higher duration for map + filter
  },
  {
    name: 'profileReduce',
    entryType: 'measure',
    startTime: 310667.7550000022,
    duration: 24.754999991273507, // reduce seems slightly more efficient
  },
]

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...