Home > Software design >  How to optimize duplicate TS checks if the value may be undefined
How to optimize duplicate TS checks if the value may be undefined

Time:02-05

Can the following code be simplified for readability, simplicity, or any other way? Specifically, can this be written without checking for undefined on every line?

These ok statements are only some of the many filters that are checked, so this list is large and unruly.

  const aOk = data?.a ? data.a.includes(a) : true
  const bOk = data?.b ? data.b <= b : true
  const cOk = data?.c ? data.c >= c : true
  const dOk = data?.d ? data.d === d : true
  const eOk = data?.e ? data.e === e.toString() : true

  if (
    aOk &&
    bOk &&
    cOk &&
    dOk &&
    eOk
  ) {
    return true
  }

  return false

CodePudding user response:

You could create a helper function such as

const fn = (data) = (key, op, value) =>
  data[key] ? op(data[key], value) : true

Then you can define a set of functions that do the comparisons you need. This might remove repetition, and improve maintainability. You may be able to use something like operations[key](this[key], data[key]) if your variables in data and the scope match up.

const comp = fn(data)

const aOk = comp(‘a’, myIncludes, a)

CodePudding user response:

If the shape of validation doesn't change often, I don't see a problem with your function. As another poster mentioned you can instead create a list of functions. Something like this:

type TData = {
  a: number[];
  b: number;
  c: number;
  d: number;
  e: string;
};

const data = {
  a: [3],
  b: 4,
  c: 4,
  d: 1,
  e: "9",
};

const validators: (data:TData, v: { [k in keyof TData]: number }) => {
  [k in keyof TData]: () => boolean;
} = (v) => ({
  a: () => data.a.includes(v.a),
  b: () => data.b <= v.b,
  c: () => data.c >= v.c,
  d: () => data.d === v.d,
  e: () => data.e === v.e.toString(),
});

const all = () => {
  for (const k of Object.values(validators(data, otherData))) {
    if (!k()) return false;
  }
  return true;
};

CodePudding user response:

This seems clear and is readable to me:

TS Playground

const allOk = Boolean(
  data?.a ? data.a.includes(a) : true
  && data?.b ? data.b <= b : true
  && data?.c ? data.c >= c : true
  && data?.d ? data.d === d : true
  && data?.e ? data.e === e.toString() : true
);
  •  Tags:  
  • Related