有没有办法判断javascript函数是否使用rest参数?

4dbbbstv  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(332)

我正在使用一个库来解析命令并将函数应用于它们的参数,它会在应用函数之前检查参数的数量是否正确。它通过检查 length 函数的参数。但是,如果我传入一个变量函数,当我传入任何参数时,该检查都会失败,因为 length 不包括rest参数。
是否有一种方法可以检查函数是否使用rest参数来显式处理数量可变的参数?
复制:

function call_function(f, ...args) {
  if (f.length === args.length) {
    f(...args);
  } else {
    console.log("error! wrong number of arguments!");
  }
}

function normal_function(arg1) {
  console.log("here's the argument: ", arg1);
}

function variadic_function(...args) {
  console.log("here are the arguments: ", ...args);
}

call_function(normal_function, "hello"); // here's the argument: hello
call_function(variadic_function, "hello"); // error! wrong number of arguments!
call_function(variadic_function, "hello", "there"); // error! wrong number of arguments!

normal_function("hello"); // here's the argument: hello
variadic_function("hello"); // here are the arguments: hello
variadic_function("hello", "there"); // here are the arguments: hello there
webghufk

webghufk1#

对于正则表达式,我不是很在行,但我认为在大多数情况下,类似的方法都会奏效:

const isVariadicFunction = f => /\.{3}[a-zA-Z0-9$_]+\s*\)/.test(f.toString());

function call_function(f, ...args) {
  if (f.length === args.length || isVariadicFunction(f)) {
    f(...args);
  } else {
    console.log("error! wrong number of arguments!");
  }
}

function normal_function(arg1) {
  console.log("here's the argument: ", arg1);
}

function variadic_function(...args) {
  console.log("here are the arguments: ", ...args);
}

call_function(normal_function, "hello");
call_function(variadic_function, "hello");
call_function(variadic_function, "hello", "there");

相关问题