DEV Community

Discussion on: You Might Not Need Lodash

Collapse
 
antjanus profile image
Antonin J. (they/them) • Edited

Yeah, I was thinking about posting code snippets that replace Lodash but then I quickly realized that Lodash is SUPER lightweight to begin with and can do this stuff much better than any snippet I can write. Plus docs/tests/code coverage/edge case solutions are part of using Lodash.

You can check it out here and for convenience, here's a copy:

    function baseFlatten(array, depth, predicate, isStrict, result) {
      var index = -1,
          length = array.length;

      predicate || (predicate = isFlattenable);
      result || (result = []);

      while (++index < length) {
        var value = array[index];
        if (depth > 0 && predicate(value)) {
          if (depth > 1) {
            // Recursively flatten arrays (susceptible to call stack limits).
            baseFlatten(value, depth - 1, predicate, isStrict, result);
          } else {
            arrayPush(result, value);
          }
        } else if (!isStrict) {
          result[result.length] = value;
        }
      }
      return result;
}
Collapse
 
gsonderby profile image
Gert Sønderby

I admit I hesitate to call that bit lightweight, at least in terms of reading and understanding it.😀

Your point re. testing and edge cases and so forth is well seen. My example was mainly to give an alternative where a native function does not currently exist.

Thread Thread
 
antjanus profile image
Antonin J. (they/them) • Edited

Lightweight in size! Especially if you import only what you need. eg:

// import directly what you need
import clone from 'lodash/clone';

// or if you have tree shaking
import { clone } from 'lodash';

// or if you use the lodash babel plugin
import _ from 'lodash';

//and then use it!

Reading it isn't too bad but their looping is bizarre to me. It's done for memory/speed use but counting down from a number in a while loop instead of doing a for loop baffles me but I understand they have reasons for it.