Refactor getLegalValues

Benchmark created on


Setup

function orderAndForEachOfKeys(legalKeys, nonIndexedLegalKeys, legalValues) {
  const dictionary = {
    legal: {},
    nonIndexedLegal: {},
  };

  legalKeys.forEach((key, i) => {
    dictionary.legal[key] = {
      index: i,
      key,
      value: legalValues.find((v) => v.fields.slug === key).fields.body,
    };
  });

  nonIndexedLegalKeys.forEach((key) => {
    dictionary.nonIndexedLegal[key] = {
      value: legalValues.find((v) => v.fields.slug === key).fields.body,
    };
  });

  return dictionary;
}

function orderAndForEachOfValues(legalKeys, nonIndexedLegalKeys, legalValues) {
  const dictionary = {
    legal: {},
    nonIndexedLegal: {},
  };

  legalValues.forEach(({ fields: { slug, body } }) => {
    const isIndexed = legalKeys.indexOf(slug) !== -1;
    if (isIndexed)
      dictionary.legal[slug] = {
        index: legalKeys.indexOf(slug),
        key: slug,
        value: body,
      };
    else
      dictionary.nonIndexedLegal[slug] = {
        value: body,
      };
  });

  return dictionary;
}

function sortAndUnwrap(legalKeys = [], nonIndexedLegalKeys, legalValues) {
  const dictionary = {
    legal: {},
    nonIndexedLegal: {},
  };

  const items = [];
  const keys = legalKeys.concat(nonIndexedLegalKeys);

  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const item = legalValues.find((item) => item.fields.slug === key);

    if (!item) continue;

    items.push(item.fields);
  }

  let legalIndex = 0;
  for (const legalValue of items) {
    const key = legalValue.slug;
    const isLegal = legalKeys.includes(key);

    if (isLegal && !(key in dictionary.legal)) {
      dictionary.legal[key] = {
        index: legalIndex++,
        key: legalValue.slug,
        value: legalValue.body,
      };
    } else if (!isLegal && !(key in dictionary.nonIndexedLegal)) {
      dictionary.nonIndexedLegal[key] = {
        key: legalValue.slug,
        value: legalValue.body,
      };
    }
  }

  return dictionary;
}

const legalKeys = ['sample-legal-key'];
const nonIndexedLegalKeys = ['sample-non-indexed-legal-key'];

const legalValues = [
  {
    fields: {
      title: 'Legal',
      slug: 'sample-legal-key',
      body: 'This is a test legal body',
    },
  },
  {
    fields: {
      title: 'Non-indexed legal',
      slug: 'sample-non-indexed-legal-key',
      body: 'This is a test non-indexed legal body',
    },
  },
]

Test runner

Ready to run.

Testing in
TestOps/sec
For Each Value - After Refactor
orderAndForEachOfValues(legalKeys, nonIndexedLegalKeys, legalValues)
ready
For Each Key - After Refactor
orderAndForEachOfKeys(legalKeys, nonIndexedLegalKeys, legalValues)
ready
Before Refactor
sortAndUnwrap(legalKeys, nonIndexedLegalKeys, legalValues)
ready

Revisions

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