Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
javascript implementation of Ruby 1.9's tap
Object.defineProperty(Object.prototype, 'tap', {
value: function(fun){
fun.call( this );
return this;
},
enumerable: false
});
// Usage:
// a = [];
// a.tap(function(){ this.push('foo'); });
// a => [ 'foo' ]
@kleinron

This comment has been minimized.

Copy link

@kleinron kleinron commented Feb 2, 2021

I'd add the following to the usage:

b = [];
b.tap(function(x){ x.push('foo'); });
// b => [ 'foo' ]
@evilbuck

This comment has been minimized.

Copy link
Owner Author

@evilbuck evilbuck commented Feb 2, 2021

I'd add the following to the usage:

b = [];
b.tap(function(x){ x.push('foo'); });
// b => [ 'foo' ]

I don't believe that would actually work with this implementation. x would be undefined as there are not any arguments passed to the fun.

@kleinron

This comment has been minimized.

Copy link

@kleinron kleinron commented Feb 2, 2021

I'd add the following to the usage:

b = [];
b.tap(function(x){ x.push('foo'); });
// b => [ 'foo' ]

I don't believe that would actually work with this implementation. x would be undefined as there are not any arguments passed to the fun.

You're right. I mistakenly thought it also accepts the object itself as an argument.
But I think it should have this argument, as this is what Ruby's tap is all about - to intercept the call chain with the "current" object.

@evilbuck

This comment has been minimized.

Copy link
Owner Author

@evilbuck evilbuck commented Feb 2, 2021

I'd add the following to the usage:

b = [];
b.tap(function(x){ x.push('foo'); });
// b => [ 'foo' ]

I don't believe that would actually work with this implementation. x would be undefined as there are not any arguments passed to the fun.

You're right. I mistakenly thought it also accepts the object itself as an argument.
But I think it should have this argument, as this is what Ruby's tap is all about - to intercept the call chain with the "current" object.

Ahh. Yes. I think I remember implementing it incorrectly after the fact when I typed this up 8 years ago. Thanks for the feedback. I'll need to look up how Ruby tap works again. I haven't used ruby in about 5 years.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment