can you define a function expression with multiple anonymous functions stored (perhaps attached by an operator) in one variable? if so, how do you pass arguments to the functions?
Function expressions can be cached in the same way any other values can. We can have an array filled with nothing but function expressions. An object can have a unlimited number of methods which are essentially function expressions but tied to the object.
In other words, any thing that can be referenced can hold functions.
This will be a bit of silliness but let’s say we have an array of function expressions.
let func = [ x => x * 5, x => x / 5, x => x + 5, x => x - 5, x => x ** 0.5 ]
Now let’s say we have the user input one of these operators, and in another input, a number.
let op = prompt("* | / | + | - | r"); let num = prompt("Enter a number:");
Now using the information provided we can invoke a function on the value they entered.
We can of course refine this to include validation, but the gist is basically what we see here.
Guess I better go off and test this to make sure it works. Above is theoretical, but should work.
> op = prompt("* | / | + | - | r") <- "r" > num = prompt("Enter a number:") <- "25" > func['*/+-r'.indexOf(op)](num) <- 5
Expected result? Check.
In all the thousands of posts I’ve written there are a handful of examples similar to this one that were essentially invented on the fly like above. This question does come up periodically and my response would likely be seat of the pants. I’m more like a cloud than a fountain.
Here is one written in Python that actually deals with roughly the same idea in process, if not in expression. Python has
lambdas that could be packaged the same way we did with the arrow functions above, but in this example I went with enclosed definitions in the function.
Don’t try too hard to understand the code, as much as the illustration. You will see parallels with the above idea.