Search code examples
javascriptnode.jsarraysjavascript-objects

How to map an response when It's array and when It's not?


I just coded two simple functions to validate a field if it has a specific value, but in some cases the responses could be a array. Can I simplify these function in just one function? I tried to use the same "isOrderInLastMile" function when the response is just a object but I retrieve the "object.map is not a function" error.

function 1: I use this function when the response is an array of objects.

export function isOrderInLastMile(pieces: any): boolean {
  const totalPieces: number = pieces.length;
  let momentFound: number = 0;

  pieces.map((element) => {
    if (
      element.stagesHistory &&
      getCurrentMoment(element.stagesHistory) ===
        MomentsLabel.En_última_milla_id
    ) {
      momentFound = momentFound + 1;
    }
    return momentFound;
  });

  return totalPieces === momentFound;
}

Function 2: I use this function when this response is just an object

export function isPieceInLastMile(piece: any): boolean {
  return (
    piece.stagesHistory &&
    getCurrentMoment(piece.stagesHistory) === MomentsLabel.En_última_milla_id
  );
}

How Can I unify both functions? Thanks!!! :)


Solution

  • Either wrap your single element in an array, like this:

    export function isPieceInLastMile(piece: any): boolean {
      return isOrderInLastMile([piece]);
    }
    

    or use the single function in a callback

      return pieces.every(isPieceInLastMile);
    

    (The latter option can be used instead of counting all matching items)