0

I am writing a function that will sort an array of objects either by property or method value. The following code is working. But how do I improve it? I feel there is a lot of duplicate code in it.

 transform(array: any, field: string): any[] {
  if (!Array.isArray(array)) {
    return;
  }
  array.sort((a: any, b: any) => {
    if (typeof a[field] == 'function' && typeof b[field] == 'function') {
      if (a[field]() < b[field]()) {
        return -1;
      } else if (a[field]() > b[field]()) {
        return 1;
      } else {
        return 0;
      }
    }
    if (a[field] < b[field]) {
      return -1;
    } else if (a[field] > b[field]) {
      return 1;
    } else {
      return 0;
    }
  });
  return array;
}
2

1 Answer 1

1
  const callOrTake = it => typeof it === "function" ? it() : it;  
  const compare = (a, b) => a === b ? 0 : (a > b ? 1 : -1); 
  const transform = <T> (array: T[], field: keyof T) => array.sort((a, b) => compare(callOrTake(a[field]), callOrTake(b[field])));

The following improvements were made:

(1) Calling the field if it is a function was moved to it's own function to avoid repetition.

(2) The signature of transform was improved so that field cannot be any string, but has to be a key of whatever is inside the array.

Sign up to request clarification or add additional context in comments.

1 Comment

I was trying to build an Angular Pipe. It would seem that both compare and callOrTake are inaccessible from the anonymous function inside sort. IDK but that just might have something do with Angular. I am still going to accept your answer bcz it has all the necessary elements for improving the original code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.