1

Running into a weird situation with lodash (v4.6.1) where I'm passing in a _.partialRight function of _.padStart into a _.map callback and getting bum results.

Repro:

_.padStart("0", 2, "0");
// "00"
var f = _.partialRight(_.padStart, 2, "0");
f("0");
// "00"
_.map(["0"], function(s) { return f(s); });
// ["00"]
_.map(["0"], f);
// ["0"]

After diving into the lodash code that's doing this, we come to here:

function arrayMap(array, iteratee) {
  var index = -1,
      length = array.length,
      result = Array(length);

  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}

At this point iteratee is the f function declared above. Without diving into the code much further than that, I can only assume the arguments added on from _.partialRight are getting appended after any and all arguments called on that function.

And now we reach the question part. Is this a bug/limitation with lodash or is there a better way to do this?

Enlico
  • 23,259
  • 6
  • 48
  • 102
nwayve
  • 2,291
  • 23
  • 33

1 Answers1

1

After some investigation, it looks like in order to accomplish this, without wrapping the resulting function from _.partialRight in a function, is to utilize the _.ary function to limit the arguments it will accept. So the final result would look like this:

var f = _.ary(_.partialRight(_.padStart, 2, '0'), 1);
var result = _.map(["0"], f);
// result == ["00"]

and to take it a step further to reduce the ugliness in code usage:

_.mixin({
  "padStartTwoZeroes": _.ary(_.partialRight(_.padStart, 2, '0'), 1)
});

var numbers = [0, 5, 10];
var paddedNumbersAsStrings = _.map(numbers, _.padStartTwoZeroes);

But maybe with more elegant naming or a more generic mapPadStart that you could manually set the number and characters to pad with.

Anyways, lodash never ceases to amaze me with its capabilities and flexibility.

nwayve
  • 2,291
  • 23
  • 33
  • I've asked [a new question](https://stackoverflow.com/q/70324531/5825294) before finding this one of yours. I hope I'll get an answer as to what causes the limitation you've found. – Enlico Dec 12 '21 at 14:44