Reputation: 426
I need to limit the argument of the functions in my js.Is there any way to set the function arguments limitation while invoking.
Upvotes: 0
Views: 71
Reputation: 7916
No. You can never really limit the accepted number of arguments. Any function will simply run with any amount of arguments.
You can however create a higher order function that wraps a function in order to control the number of arguments the wrapped function receives:
function limitArgs(maxArgs, fn) {
return function(...allArgs) {
const limitedArgs = allArgs.slice(0, maxArgs);
return fn(...limitedArgs);
};
}
When this function limitArgs
is invoked the following happens:
maxArgs
, that defines how many arguments the wrapped function must receive at most.fn
, which is the function to limit the arguments for.maxArgs
> arguments that the function was given. It will then call fn
spreading only the created arguments array.Working example:
// As arrow function oneliner this time:
const limitArgs = (maxArgs, fn) => (...allArgs) => fn(...allArgs.slice(0, maxArgs));
const testFn = (...args) => console.log(`Arguments given: [${args}]`);
const testFn4 = limitArgs(4, testFn);
testFn4(1, 2, 3, 4, 5);
// Expected output: 'Arguments given: [1,2,3,4]'
const testFn2 = limitArgs(2, testFn);
testFn2(1, 2, 3, 4, 5);
// Expected output: 'Arguments given: [1,2]'
Upvotes: 1
Reputation: 1210
You could use another function as a "middleware function"
function invoker(func, ...args) {
if (args.length > 4) throw new Error('Too many arguments!');
else if (typeof(func) === "function") func.apply(null,args)
}
function foo (...args) {
console.log(args.length)
}
Run invoker(foo, 1,2,3,4,5)
will throw an error.
Run invoker(foo, 1,2,3,4)
will run foo(1,2,3,4)
Upvotes: 0
Reputation: 33726
Is there a way to allow a function to accept definite number of arguments in js
No, you can't. However, there is a limitation of the amount of arguments and it's implementation dependent (browsers, backend tech, Etc,.).
An alternative is checking the length of the implicit arguments
array within a function (non arrow-functions).
For example:
I'm assuming you want to throw an Error
function fn(a, b, c) {
if(arguments.length > 3) throw new Error('Too many arguments!');
console.log(arguments[0], arguments[1], arguments[2]);
}
fn('Ele', 'from', 'SO'); // Will work!
fn('Ele', 'from', 'SO', 'Hello!'); // Won't work!
Upvotes: 0