Return Length of Arguments Passed Problem
#2703
Description
LeetCode Problem 2703.
Write a function argumentsLength that returns the count of arguments passed to it.
Example 1:
Input: args = [5]
Output: 1
Explanation:
argumentsLength(5); // 1
One value was passed to the function so it should return 1.
Example 2:
Input: args = [{}, null, "3"]
Output: 3
Explanation:
argumentsLength({}, null, "3"); // 3
Three values were passed to the function so it should return 3.
Constraints:
argsis a valid JSON array0 <= args.length <= 100
Solution
Approach: Rest parameters
A rest parameter ...args collects every argument passed to the function into a real array, so the answer is args.length. It works for zero arguments, and for values such as null or undefined that still count as passed.
Complexity: Time O(n) to collect the arguments, space O(n).
var argumentsLength = function (...args) {
return args.length;
};