w3resource

JavaScript: Create a function that invokes the method at a given key of an object

JavaScript fundamental (ES6 Syntax): Exercise-60 with Solution

Write a JavaScript program to create a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.

  • Return a function that uses Function.prototype.apply() to bind context[fn] to context.
  • Use the spread operator (...) to prepend any additional supplied parameters to the arguments.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const bindKey = (context, fn, ...args) =>
  function() {
    return context[fn].apply(context, args.concat(...arguments));
  };

const freddy = {
  user: 'fred',
  greet: function(greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
  }
};
const freddyBound = bindKey(freddy, 'greet');
console.log(freddyBound('hi', '!'));

Sample Output:

hi fred!

Flowchart:

flowchart: Create a function that invokes the method at a given key of an object

Live Demo:

See the Pen javascript-basic-exercise-60-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to create a function that invokes fn with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
Next: Write a JavaScript program to cast the provided value as an array if it's not one.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

Chunks an array into n smaller arrays

Example:

const tips_chunkIntoN = (arr, n) => {
  const size = Math.ceil(arr.length / n);
  return Array.from({ length: n }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
}
console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4)); 

Output:

[[1,2],[3,4],[5,6],[7,8]]