DEV Community

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

Posted on

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

Nota: apenas traduzi o texto abaixo e postei aqui.

Apenas por diversão, comecei a examinar métodos em lodash e a criar equivalentes vanilla JS.

Hoje, vamos recriar o método lodash _.pull() com vanilla JS.

O que esse método faz

O método _.pull() pega um array e remove quaisquer valores que match ao que você passa.

var array = ['a', 'b', 'c', 'a', 'b', 'c'];
_.pull(array, 'a', 'c');

// Loga ['b', 'b']
console.log(array);
Enter fullscreen mode Exit fullscreen mode

Um método pull() vanilla JS

Para este, usaremos o método Array.filter().

Primeiro, vamos criar um método helper pull(). Ao contrário da versão lodash, passaremos um array para valores.

var pull = function (array, values) {
    // Faça coisas...
};
Enter fullscreen mode Exit fullscreen mode

A seguir, chamaremos o método Array.filter() no array que foi passado.

var pull = function (arr, values) {
    return arr.filter(function (item) {
        // Faça coisas...
    });
};
Enter fullscreen mode Exit fullscreen mode

Por fim, verificaremos se o item atual está no array de valores a serem removidos usando o método Array.indexOf().

Se o método for maior que 0, retornaremos um valor false. Caso contrário, retornaremos um valor true.

var pull = function (arr, values) {
    return arr.filter(function (item) {
        return values.indexOf(item) < 0;
    });
};

// versão sem o uso de filter
var pullNoFilter = function (arr) {
    var output = arr.concat([]);
    for (var i = 1; i < arguments.length;i++) {
        var item = arguments[i];
        do {
           var index = output.indexOf(item);
           index > -1 && output.splice(index, 1);
        } while (index > -1);
    }
    return output;
};
Enter fullscreen mode Exit fullscreen mode

Ao contrário da versão lodash, isso retorna um novo immutable array, então precisaremos atribuí-lo a uma variável.

Agora podemos fazer isso.

var array = ['a', 'b', 'c', 'a', 'b', 'c'];
var pulled = pull(array, ['a', 'c']);

// Loga ['b', 'b']
console.log(pulled);
Enter fullscreen mode Exit fullscreen mode

Fonte

Newsletter de Go Make Things

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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