This is continuation of this question with more difficult case. Suppose I want to call string function with 2 parameters e.g.
Yes, it is possible.
So we start with the expression that omits the comma, and only consists of string literals and the JSF characters:
["true"]["concat"]("1")["reduce"](""["replace"]["bind"]("truefalse"))
For a moment, I will phrase this expression using the more readable dot notation, and go back to the comma separator for array literals:
["true", "1"].reduce("".replace.bind("truefalse"))
This has the input of the replacement, i.e. "truefalse", sitting at the end. The parameters, on the other hand, are located at the left, i.e. "true" and "1". We could try to make "truefalse" also an argument, so that we could move it to the left.
For that purpose we can use "".replace.apply
instead of "".replace
as callback to reduce
. The first argument of apply
is the this
-binding for the replace
call. The second argument should be the array of arguments to pass to replace
, so that is the array we currently have at the left.
And then the apply
method itself should also get a this
-binding. We get this expression:
console.log(
["truefalse", ["true", "1"]].reduce("".replace.apply.bind("".replace))
);
NB: "".replace.apply
could reference any other function instead of replace
, as long as it is a function. We just need a way to reference the Function.prototype.apply
function.
So, we have succeeded to move the "truefalse" expression more to the front. But it really should not sit in an array literal if we want to achieve non-nested chaining.
Here we can use a "feature" of the split
method: if you don't pass any argument, it returns an array with the original string. Exactly what we need.
So:
console.log(
"truefalse".split().concat([["true", "1"]]).reduce("".replace.apply.bind("".replace))
);
Now we can chain!
So, to finalise, here is the same expression with the dots and commas removed:
console.log(
"truefalse"["split"]()["concat"]([["true"]["concat"]("1")])
["reduce"](""["replace"]["apply"]["bind"](""["replace"]))
);
...and to chain, you just continue the expression with ["split"]()
...etc.