pseudo rest parameters with CFML

January 18, 2019
I try to bend the internet to my will.
Wizard 26 posts
Followers: 19 people
0

pseudo rest parameters with CFML

I try to bend the internet to my will.
Wizard 26 posts
Followers: 19 people
January 18, 2019

In Javascript there is the rest parameter syntax, which is useful when you have a method which can accept multiple additional arguments. Have a look at the example of MDN to see how it works.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

CFML does not support the rest or spread syntax, but I thought I’d have a go at doing an approximation with CFML. It’s a bit clunky and it’s not that clear what arguments the method accepts so I wouldn’t recommend using this approach unless you have to, but it does the job.

    
function foo(first /* , ...rest*/) {
    var args = structCopy(arguments);
    structDelete(args, "first");
    var rest = args.reduce(function(accumulator, el) {
            return accumulator.append(args[el]);
        }, []);
    return {
        first: first,
        rest: rest
    };
}

result = foo("apple","bean","carrot","date");
writeDump(result);

The output from the function is:

function output

Here’s a runnable example:

https://trycf.com/gist/a1e03fd81465c73a64ae702b5fd7016a/acf2018?theme=monokai

In case you are wondering, the `/*, …rest*/` in the functions arguments doesn’t actually do anything (it’s a comment), I’ve put it in there so that if someone was to read this code, it would give them a clue as to how to call the function.

Comments (0)
Add your comment