Array#invoke Useful JavaScript Game Extension #24

Array#invoke is a method to make the common task of inoking a method on all elements in an array easier. Though you could use your own anonymous function as a map or each iterator to achieve the same result, this shortcut method makes it clear what the intention is and removes the extra syntax clutter.

What invoke does is to call the named method on each element in the array, passing in any arguments if given.

/**
* Invoke the named method on each element in the array
* and return a new array containing the results of the invocation.
*
* @param {String} method The name of the method to invoke.
* @param [arg...] Optional arguments to pass to the method being invoked.
*
* @type Array
* @returns A new array containing the results of invoking the
* named method on each element.
*/
Array.prototype.invoke = function(method) {
  var args = Array.prototype.slice.call(arguments, 1);

  return this.map(function(element) {
    return element[method].apply(element, args);
  });
};

Here are some examples of it in action:

[1.1, 2.2, 3.3, 4.4].invoke("floor")
=> [1, 2, 3, 4]

['hello', 'world', 'cool!'].invoke('substring', 0, 3)
=> ['hel', 'wor', 'coo']

The result of each invocation is returned in an array. This allows for easy chaining of data transformations:

values.invoke("scale", 4).invoke("subtract", 3)...

Fans of Ruby and Rails will know about Symbol#to_proc, a closely related idiom:

names = people.map &:name

Thanks for reading!

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: