3 ms·
But – A way to pass along a callback with just a single argument
- kemitchell 12y agoSigh ... module.exports = function (fn) { return function (first) { fn(first); }; };
- bevacqua 12y agoThere's also `butt` if you have more complicated needs. Feel free to use it. https://github.com/bevacqua/butt https://github.com/bevacqua/butt
- dyscrete 12y agoWhy not allow an optional 2nd argument that defaults to 1 on your `but` library to do this?
- bevacqua 12y agoThat's what butt does! `but` doesn't do this because to be honest it's quite rare that you'll need it. and it's also butt-ugly to do that.
- aaronem 12y agoWhy complicate things? If it means so much to you, you can just var butt = require('butt'); var but = function(fun) { return butt(fun, 1); }; or even var but = function(fun) { return function(arg) { return fun(arg); }; };
- nescalante 12y agoExtremely powerful library
- chingjun 12y agoCan anyone explain to me why I couldn't write n.forEach(console.log); Just tested on Chrome, it gives me an error TypeError: Illegal invocation
- nilved 12y agoWhen you use `console.log` that way it gets `this` set to `null`. When you call `console.log("hello")`, `this` is set to `console`. Your code would work if you set an explicit `this`. n.forEach(console.log.bind(console)); I don't think there's any reason for this library to exist after you understand `this` semantics but I may be missing something. e: was, in fact, missing something. Apologies for the disparaging comment, see replies.
- bevacqua 12y agoThat's one, the other is that many of those functional methods tend to mess with functions that take more than one argument when you want to use the first one, e.g parseInt.
- dyscrete 12y agoWell it's not just about `this` but the arguments to pass to console rather. In this case: n.forEach(console.log.bind(console)); forEach is passing console all of its callback arguments, resulting in logging of keys, values, and array. EDIT: Forgot array
- nilved 12y agoAh, I understand. It reminds me of how the `cut` function could be used in Scheme.
- willyg302 12y agoAdditionally, this will log all the passed arguments (value, index, and array being traversed), which typically isn't what you want: [1, 2, 3].forEach(console.log.bind(console)); > 1 0 [1, 2, 3] > 2 1 [1, 2, 3] > 3 2 [1, 2, 3]
- aaronem 12y agoConvenience, I suppose; I had a few headaches when I first transitioned to Javascript and discovered the odd signatures its collection functions' callbacks are expected to have.
- escape_goat 12y agofunction butter (){ fn=arguments[0]; return function(){ var args = []; for( var n=1; n<arguments.length; n++ ) { args.push(arguments[n]); }; return fn.apply(this,args) } } edit: I know my loop is totally anachronistic, but I'm short on time for testing this.
- 12y ago