Nth argument

JavaScript, Function · Oct 21, 2020

Creates a function that gets the argument at index n.

  • Use Array.prototype.slice() to get the desired argument at index n.
  • If n is negative, the nth argument from the end is returned.
const nthArg = n => (...args) => args.slice(n)[0];
const third = nthArg(2);
third(1, 2, 3); // 3
third(1, 2); // undefined
const last = nthArg(-1);
last(1, 2, 3, 4, 5); // 5

More like this

  • Rearrange function arguments

    Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

    JavaScript, Function · Oct 22, 2020

  • Transform function arguments

    Creates a function that invokes the provided function with its arguments transformed.

    JavaScript, Function · Oct 21, 2020

  • Bind object method

    Creates a function that invokes the method at a given key of an object, optionally prepending any additional supplied parameters to the arguments.

    JavaScript, Function · Oct 18, 2020