Référence rapide

Aide-mémoire Lodash

Guide complet pour Lodash : méthodes de collection, transformations de tableaux, curryfication, throttling, utilitaires de chaînes et chaînage.

· Publié le

Lodash est une bibliothèque utilitaire JavaScript moderne offrant modularité et performance pour manipuler tableaux, nombres, objets et chaînes.

Collections

Les fonctions de collection s'appliquent uniformément aux tableaux comme aux objets.

Recherche et filtrage

_.filter(list, (n) => n % 2 === 0);   // -> Array of matches
_.find(list, (n) => n % 2 === 0);     // -> First matching item
_.findLast(list, (n) => n % 2 === 0); // -> Last matching item
_.reject(list, (n) => n % 2 === 0);   // -> Array with matches excluded

Accès profond et mutation

// Safe path access
_.get(object, 'users[0].name', 'Default');
_.get(object, ['users', 0, 'name']);

// Set value at deep path
_.set(object, 'users[0].name', 'Alice');

// Extract elements at paths
_.at({ a: [{ b: { c: 3 } }] }, ['a[0].b.c']); // -> [3]

Itération et prédicats

_.forEach(list, (item, index) => { /* ... */ });
_.forEachRight(list, (item) => { /* ... */ });

_.map(list, (item) => item.id);

_.every(users, (u) => u.active); // -> Boolean (all match)
_.some(users, (u) => u.active);  // -> Boolean (at least one matches)

Tableaux

Découpage et segmentation

_.chunk(['a', 'b', 'c', 'd'], 2);  // -> [['a', 'b'], ['c', 'd']]
_.compact([0, 1, false, 2, '', 3]); // -> [1, 2, 3] (removes falsy values)

_.drop([1, 2, 3, 4], 2);           // -> [3, 4]
_.take([1, 2, 3, 4], 2);           // -> [1, 2]

Opérations sur les ensembles

_.uniq([2, 1, 2]);                       // -> [2, 1]
_.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); // -> [{ x: 1 }, { x: 2 }]

_.difference([2, 1], [2, 3]);            // -> [1]
_.intersection([2, 1], [2, 3]);          // -> [2]
_.union([2], [1, 2]);                    // -> [2, 1]

Fonctions

Curryfication et application partielle

const greet = (greeting, name) => `${greeting}, ${name}!`;
const curriedGreet = _.curry(greet);

const sayHello = curriedGreet('Hello');
sayHello('Alice'); // -> "Hello, Alice!"

Throttling et Debouncing

// Debounce: Wait for 300ms of inactivity before firing
const onSearch = _.debounce(searchApi, 300);

// Throttle: Fire at most once every 200ms
const onScroll = _.throttle(updateScrollPosition, 200);

// Once: Function that can only be invoked once
const initialize = _.once(setupApp);

Mise en cache (Mémoïsation)

const fibonacci = _.memoize((n) => {
  return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

Chaînes

Casse des caractères

_.camelCase('Foo Bar');   // -> "fooBar"
_.kebabCase('Foo Bar');   // -> "foo-bar"
_.snakeCase('Foo Bar');   // -> "foo_bar"
_.startCase('fooBar');    // -> "Foo Bar"
_.capitalize('fred');     // -> "Fred"

Remplissage et rognage

_.pad('abc', 8);          // -> "  abc   "
_.padStart('abc', 6, '_'); // -> "___abc"
_.trim('  abc  ');        // -> "abc"
_.trim('-_-abc-_-', '_-'); // -> "abc"

Objets

Clés, valeurs et inversion

_.keys({ a: 1, b: 2 });       // -> ['a', 'b']
_.values({ a: 1, b: 2 });     // -> [1, 2]
_.invert({ a: 'x', b: 'y' }); // -> { x: 'a', y: 'b' }

Fusion et clonage

// Shallow clone vs deep clone
const shallow = _.clone(user);
const deep = _.cloneDeep(user);

// Deep merge
_.merge({ a: [{ b: 1 }] }, { a: [{ c: 2 }] }); // -> { a: [{ b: 1, c: 2 }] }

// Pick and omit
_.pick(user, ['name', 'email']);
_.omit(user, ['password', 'salt']);

Chaînage (Chaining)

Enchaînez plusieurs opérations avec _.chain() et récupérez le résultat final avec .value() :

const youngestUsers = _(users)
  .filter((u) => u.active)
  .sortBy('age')
  .map((u) => `${u.name} is ${u.age}`)
  .head()
  .value();

Références

Sujets associés