DEV Community

Cover image for Recriando o método lodash inRange() em vanilla JS
doug-source
doug-source

Posted on

Recriando o método lodash inRange() em vanilla JS

Nota: apenas traduzi o texto abaixo e postei aqui.

Hoje vamos recriar o método inRange() com vanilla JS.

O que _.inRange() faz

O método lodash _.inRange() pega um number e verifica se está entre dois outros numbers.

Você passa o number, o start do range e o end do range como arguments.

_.inRange(number, start, end);

// Retorna true
_.inRange(2, 1, 4);

// Retorna false
_.inRange(2, 3, 5);
Enter fullscreen mode Exit fullscreen mode

Você também pode pular o start e passar apenas o end. O método usará 0 como start por padrão.

// Retorna true
_.inRange(2, 4);
Enter fullscreen mode Exit fullscreen mode

Se o number for igual ao start do range, ele passa. Se for igual ao end, ele falha. Pessoalmente, isso me parece estranho.

// Retorna true
_.inRange(2, 2, 4);

// Retorna false
// Porque?????
_.inRange(4, 2, 4);
Enter fullscreen mode Exit fullscreen mode

Tudo bem, vamos fazer isso.

Recriando _.inRange() com vanilla JS

Primeiro, vamos configurar nossa helper function.

var inRange = function (num, start, end) {
    // Faça as coisas...
};
Enter fullscreen mode Exit fullscreen mode

A seguir, vamos verificar se nosso number está no range.

Acho que o end deve ser inclusivo, assim como o start, então faremos as coisas de maneira um pouco diferente do que lodash faz aqui. Verificaremos se num é maior ou igual ao start e menor ou igual ao end. Então, retornaremos o resultado.

var inRange = function (num, start, end) {
    return num >= start && num <= end;
};
Enter fullscreen mode Exit fullscreen mode

A versão lodash permite "drop" o start, se desejar, e o default é 0. Vamos adicionar essa feature.

Verificaremos se end existe. Caso contrário, atribuiremos start como seu valor. Então, definiremos o start como 0.

var inRange = function (num, start, end) {
    // Se não houver o end number, use start como end
    if (!end) {
        end = start;
        start = 0;
    }
    return num >= start && num <= end;
};
Enter fullscreen mode Exit fullscreen mode

Uma última coisa que lodash faz é "flip" os valores de start e end se o start for maior que o end. Isso é feito para suportar valores negativos.

// Retorna false
inRange(-2, -1, -4);
Enter fullscreen mode Exit fullscreen mode

Neste exemplo, -1 é na verdade maior que -4, porque são números negativos. O número -2 está dentro do range, mas se os números não fossem "flipped", ele falharia.

Pessoalmente, acho que os usuários deveriam passar isso da maneira certa, então não vou apoiar essa feature.

// Retorna true
inRange(-2, -4, -1);
Enter fullscreen mode Exit fullscreen mode

Então, com isso, terminamos.

Fonte

Newsletter de Go Make Things

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay