Files
30-seconds-of-code/snippets/nthArg.md
Mathias Bynens 8ee50178f3 Avoid confusing prototype methods for static methods
Correct: `Array.from()` (it’s a static method)
Incorrect: `Array.join()` (doesn’t exist; it’s a prototype method)

This patch uses the common `#` syntax to denote `.prototype.`.
2018-09-28 15:44:12 -04:00

18 lines
400 B
Markdown

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