Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a partial function for parseInt() using underscore _

Using underscore, I want to create a partial function for parseInt so that the radix is always 10 for using with map.

I expected the following to work, but it doesn't:

var parseInt10 = _.partial(parseInt, _, 10); 

The docs seem to say that it's possible to use _ as a placeholder to skip arguments to be specified later in _.partial:

_.partial(function, *arguments)

Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. A close cousin of bind. You may pass _ in your list of arguments to specify an argument that should not be pre-filled, but left open to supply at call-time.

Testing

_.map([_, '_', undefined, null], function(x) { return _.partial(function(){ return arguments }, x, 10)('123'); })

Using _.partial(function(){ return arguments }, x, 10)('123') and replacing x with _, "_", undefined, null, I find that all these values are being passed unchanged directly as expected. I was under the impression that passing _ would mean it would not be used directly.

NOTE

I am perfectly aware I can do just something like this:

var parseInt10 = function(n) { return parseInt(n, 10); };

However, the fact that underscore's doc seem to imply that it's possible to use _.partial has me wondering what I am doing wrong.

So, am I interpreting the underscore doc wrong or is there no special value that handles skipping arguments?

like image 593
user193130 Avatar asked Apr 15 '26 15:04

user193130


1 Answers

I just decided to check the source code and it seems the placeholder feature for _.partial was added recently. Using the JS console on the underscore doc page, it worked!

var parseInt10 = _.partial(parseInt, _, 10);

Guess I just needed to upgrade to the newest version.

(To all those writing future documentations, it would be nice to inline annotations of changes with version numbers similar to jQuery or Django's docs, or at least make it more conspicuous which version is being presented)

like image 69
user193130 Avatar answered Apr 18 '26 05:04

user193130



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!