Problem#
Write a function argumentsLength
that returns the count of arguments passed to it.
Examples#
Example 1#
1
2
3
4
5
6
|
Input: args = [5]
Output: 1
Explanation:
argumentsLength(5); // 1
One value was passed to the function so it should return 1.
|
Example 2#
1
2
3
4
5
6
|
Input: args = [{}, null, "3"]
Output: 3
Explanation:
argumentsLength({}, null, "3"); // 3
Three values were passed to the function so it should return 3.
|
Constraints#
args
is a valid JSON array
0 <= args.length <= 100
Solution#
Method 1 - Rest Parameters#
Intuition#
JavaScript and TypeScript allow us to use rest parameters to capture all arguments as an array, whose length is the answer.
Approach#
Define the function with ...args
and return args.length
.
Code#
1
2
3
|
function argumentsLength(...args) {
return args.length;
}
|
1
2
3
|
function argumentsLength(...args: any[]): number {
return args.length;
}
|
Complexity#
- ⏰ Time complexity:
O(1)
— just returns the array length.
- 🧺 Space complexity:
O(1)
— no extra space used.