Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
How to pass sort direction to a function?

I have the following code:

    this.userActionsRights$ = combineLatest([this.sortBy$, this.userActionsRights$]).pipe(
        map(([sortBy, userRights]) => {
            const { active, direction } = sortBy;
            const sortByAsc = direction === 'asc';
            let sortFn;

            if (active === 'name') sortFn = compareString;
            if (active === 'id') sortFn = compareNumber;

            return userRights.sort(sortFn);
        }),
    );

Where compare string is:

export function compareString(a: string | undefined, b: string | undefined, isAsc: boolean) {
  if (a === undefined || a === null) return isAsc ? 1 : -1
  if (b === undefined || b === null) return isAsc ? -1 : 1

  return isAsc ? b.localeCompare(a) : a.localeCompare(b)
}

How to pass sortByAsc to compareString and then apply it below in userRights.sort(sortFn);.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can just create a new arrow function on the fly, like so:

this.userActionsRights$ = combineLatest([this.sortBy$, this.userActionsRights$])
  .pipe(
    map(([sortBy, userRights]) => {
      const { active, direction } = sortBy;
      const sortByAsc = direction === 'asc';
      let sortFn;

      // Here instead of passing the method directly,
      // we create a new one with the correct parameters passed
      if (active === 'name') sortFn = (a, b) => compareString(a, b, sortByAsc);
      if (active === 'id') sortFn = compareNumber;

      return userRights.sort(sortFn);
    }),
  );
about 4 years ago · Juan Pablo Isaza Relatório

0

An easy way to solve your problem would be to wrap sortFn in a function that inverts the result if the sort direction is "desc".

const userRights = /* an array */;
const sortFn = /* sort callback function that sorts asc */;
const direction = /* the sort direction */;
const modifiers = { asc: 1, desc: -1 };

// Forward the `a` and `b` arguments to `sortFn` and multiply the return
// value with the modifier.
return userRights.sort((a, b) => sortFn(a, b) * modifiers[direction]);

Note that direction must be either "asc" or "desc", otherwise NaN is returned. (A number multiplied by undefined results in NaN.)

To allow both uppercase and lowercase characters you might want to downcase the direction up front.

direction = direction.toLowerCase(); // <- you have to define direction with `let`

You probably also want to throw an error if an invalid direction is passed.

if (!(direction in modifiers)) {
  throw new Error(`Invalid sort direction "${direction}".`);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda