w3resource

JavaScript: Create a function that accepts up to n arguments, ignoring any additional arguments

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

Write a JavaScript program to create a function that accepts up to n arguments, ignoring any additional arguments.

  • Call the provided function, fn, with up to n arguments, using Array.prototype.slice(0, n) and the spread operator (...).

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
// Define a function 'ary' that takes a function 'fn' and a number 'n', returning a new function that accepts up to 'n' arguments
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));

// Define a function 'firstTwoMax' that limits the maximum number of arguments to 2 using 'ary' with 'Math.max'
const firstTwoMax = ary(Math.max, 2);

// Map over an array of arrays, applying 'firstTwoMax' to each inner array
console.log([[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x))); // [6, 8, 10] (maximum of the first two elements in each inner array)

Output:

[6,8,10]

Flowchart:

flowchart: Create a function that accepts up to n arguments, ignoring any additional arguments.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to convert a 2D array to a comma-separated values (CSV) string.
Next: Write a JavaScript program to decode a string of data which has been encoded using base-64 encoding.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-258.php