Today I Learned

A Hashrocket project

Pass arguments through to wrapped function

If you want to have a function that wraps another function it’s convenient to not worry about the details of the arguments being passed.

I have this:

sendMessage = (name, num) => () {
  console.log(name, num);

And I want to wrap it with this:

wrapper = (func, name, num) => () {
  func(name, num);

Not all functions I want to wrap have the arguments name and num. To genericize this I can use ...args in the signature to turn all the remaining args into an array and then use ...args again to spread the array into the argument positions of the function call.

wrapper = (func, ...args) => () {

To have the same operator (...) do opposite things based on the context is a little bit weird to me, but that’s ES6!

Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.