Sass 获取函数的参数数
我收到一个函数作为另一个函数的参数,我想知道它的参数数量。这可能吗 例如:Sass 获取函数的参数数,sass,Sass,我收到一个函数作为另一个函数的参数,我想知道它的参数数量。这可能吗 例如: @function foo($list, $fn) { if (number-of-arguments($fn) == 1) { // looking for this kinda magic // ... } } 为了避免XY问题,如果上述方法不可行,我尝试忽略call的错误,并提供额外的参数:call($fn,$arg1,$arg2)将失败,如果$fn定义为只接受一个参数。它当前失败的原因是:错误
@function foo($list, $fn) {
if (number-of-arguments($fn) == 1) { // looking for this kinda magic
// ...
}
}
为了避免XY问题,如果上述方法不可行,我尝试忽略
call
的错误,并提供额外的参数:call($fn,$arg1,$arg2)
将失败,如果$fn
定义为只接受一个参数。它当前失败的原因是:错误:“fn”的参数数目错误(2代表1)
。我还希望有一个try/catch机制,但在Sass中也没有这样的概念。没有内省功能,但可以进行基于地图的验证,如:
// dummy functions
@function fn1($a){ @return $a; }
@function fn2($a, $b){ @return $a + $b; }
@function fn3($a, $b, $c){ @return $a + $b + $c; }
@function foo(
$fn, // function name as string
$args... // arglist
){
// arguments passed
$args-passed: length($args);
// arguments required by functions
$args-required: map-get((
fn1: 1, // fn1 takes 1 argument
fn2: 2, // fn2 takes 2 arguments
fn3: 3 // fn3 takes 3 arguments
), $fn);
// match => make call
// no match => throw warning or error or do something else
@if $args-passed == $args-required {
@return call($fn, $args...);
} @else {
@warn 'function `#{$fn}` requires #{$args-required} arguments #{$args-passed} were passed ';
@return null;
}
}
test {
value-1: foo(fn1, 1);
value-2: foo(fn2, 1, 2);
value-3: foo(fn3, 1, 2);
}
输出:
test {
value-1: 1;
value-2: 3;
// value-3 receives null and is not printed but a warning is thrown
// "function `fn3` requires 3 arguments 2 were passed"
}