filtermap or reduce

Benchmark created on


Setup

function generateRandomString(length) {
  const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }
  return result;
}

function generateRandomEntry() {
  const entry = {};

  if (Math.random() < 0.95) {
    entry.node = {
      system: { uid: generateRandomString(Math.floor(Math.random() * 26) + 5) },
      title: generateRandomString(Math.floor(Math.random() * 26) + 5),
      url: generateRandomString(Math.floor(Math.random() * 26) + 5)
    };
  } else {
    entry.node = {};
  }

  return entry;
}

function generateRandomArray(length) {
  const array = [];
  for (let i = 0; i < length; i++) {
    array.push(generateRandomEntry());
  }
  return array;
}

const input = generateRandomArray(1000);

Test runner

Ready to run.

Testing in
TestOps/sec
reduce
const output = input.reduce((accumulator, item) => {
          return Object.keys(item.node).length > 0
            ? [...accumulator, { uid: item.node.system.uid, title: item.node.title, url: item.node.url }]
            : accumulator;
        }, []);
ready
filtermap
const output = input.filter((item) => Object.keys(item.node).length > 0).map((item) => ({ 
uid: item.node.system.uid, title: item.node.title, url: item.node.url }))
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.