Skip to content

Instantly share code, notes, and snippets.

@evilbuck
Created November 15, 2012 20:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save evilbuck/4081178 to your computer and use it in GitHub Desktop.
Save evilbuck/4081178 to your computer and use it in GitHub Desktop.
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
Copy link

kleinron commented Feb 2, 2021

I'd add the following to the usage:

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

@evilbuck
Copy link
Author

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
Copy link

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
Copy link
Author

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