DEV Community

Discussion on: Washing your code: avoid loops

Collapse
 
qm3ster profile image
Mihail Malo
const tableData =
  props.item &&
  props.item.details &&
  props.item.details.clients.reduce((acc, client) =>
    acc.concat(
      ...client.errorConfigurations.map(config => ({
        errorMessage: config.error.message,
        errorLevel: config.error.level,
        usedIn: client.client.name
      }))
    )
  );

is missing the initial value for reduce, such as a [].
And like @samuraiseoul mentioned, this is a case for a flatMap.

const tableData = props.item?.details?.clients.flatMap(
  ({ client, errorConfigurations }) =>
    errorConfigurations.map(({ error }) => ({
      errorMessage: error.message,
      errorLevel: error.level,
      usedIn: client.name
    }))
)

If you don't have your own flatMap yet, store bought is fine:

const flatMap = <T, R>(fn: (x: T) => R[], arr: T[]) => {
  const out: T[] = []
  const { push } = Array.prototype
  for (const x of arr) push.apply(out, fn(x))
}

JK, don't use this one, it's probably not very good.

Collapse
 
sapegin profile image
Artem Sapegin

Thanks for pointing the missing initializer, fixing!