I have found a piece of code in my teacher s notes and I do not understand it.
The point is to find the value for "pass" for which the function would return TRUE.
Can you please answer to my questions below(comments), so I can understand how this works?
<script type="text/javascript">
function findPassword(pass)
{
var b = 1337
//How is this function returning "min" (without the parens?)
function add(x){
b += 84
return min
}
//Same question as above...for "mod" - how is this compiling?
function min(x){
b -= 123
return mod
}
function div(x){
b /= 3
return min
}
function mod(x){
b = b+5+(b%3)
return add
}
//what is the purpose of "fn" if it is not used at all?
var fn = function ()
{
b += 34
return div
}
//WHAT is happening here? "() () ()"
(function (){
b /= 3
return mod
})()()()
if(pass == b*b) {
return true;
} else {
alert("Wrong password !")
return false;
}
}
</script>
So looking at this:
(function (){
b /= 3
return mod
})()()()
You have this:
function (){
b /= 3
return mod
}
Which is a function. You wrap it in brackets and then call it with (), this is called a immediately invoked function expression (IIFE).
So what does it return? It returns mod, which is a function, so the next () will call that function.
What does mod return:
function mod(x){
b = b+5+(b%3)
return add
}
It returns the function add, which you invoke again with (). The function add happens to return the function min, but since we have no more (), we don't invoke it, so it's basically thrown away.
Now, none of this is to suggest this is a good way to structure your code, because it isn't.
As for what value will actually make findPassword return true? Well, you could follow what happens to b in each function.
...or, you could just stick a console.log(b); right after the IIFE to see it's value. The value of pass you need will be that number squared.
Just because nobody pointed out what the purpose of the function fn in this example is:
At first sight, it may seem that you've got an anonymous function self executing, and starting a chain of execution by doing so, however, that encapsulated anonymous function, and add, are actually the only functions in the code that don't execute, and that is because the declaration of fn, before it, is missing a semicolon:
var fn = function ()
{
b += 34
return div
} // <- missing semicolon.
// Because of this, the `var` statement doesn't stop in here.
Because of that missing semicolon, the parentheses encapsulating the anonymous function that comes after this function declaration, are actually executing fn, and passing the anonymous function as an argument to it (and fn is doing nothing with that argument). So, in reality, the code looks like this:
var fn = function ()
{
console.log(arguments[0]); // Logs the anonymous function
b += 34
return div
}(function (){
b /= 3
return mod
})()()()
// The parentheses () mean 'execute' this.
// If they are chained, they execute what the previous
// function returned.
// It is possible to do that when, like in this code, the functions
// return a function reference (meaning, the name of a function).
Which is pretty much the same as this:
var fn = function () {
b += 34/= 3
return div
}( /* Executing fn... */ )( /* div */ )( /* min */ )( /* mod */ )
// fn ends up containing a reference to add, because mod returns that,
// but add is never called.
console.log(fn === add); // true
The chain of execution is this:
fn => div => min => mod
So, to arrive at the password, you do:
var b = 1337;
b += 34;
b /= 3;
b -= 123;
b = b + 5 + (b%3);
// b === 340
// password is b^2: 340 * 340 = 115600
Of course, you can also console.log b, but what's the sense of that?
Follow the return statements and you'll see that they are functions, therefore adding () to that return value will evaluate it.
The first set of parens executes the function immediately before it. This returns mod which is a function. It gets executed by the second parens. This (mod) returns add which is, again, a function. So the last set of parens executes add. Which, in the end, returns min.
It's not very clear the way this program is running but it's essentially modifying that one variable and returning more functions to simulate some logic that modifies the variable in different ways depending on how you call the functions.
Related
I came across this pattern in redux compose function. I still don't understand how in the example below the functions are evaluated starting from the last and not from the first:
function f2(a) {
return a + a;
}
function f3(a) {
return a + a + a;
}
function f4(a) {
return a + a + a + a;
}
function f5(a) {
return a + a + a + a + a;
}
function compose(...funcs) {
return funcs.reduce(function x(a, b) {
return function y(...args) {
const temp = a(b(...args));
return temp;
};
});
}
const composedFunction = compose(f2, f3, f4, f5);
const result = composedFunction(2);
In the first reduce iteration the accumulator is f2 so we'll get f2(f3(2))=12. In the next iteration we'll call f4(12)=48. In the last iteration we'll call f5(48)=240. So the evaluation order is f5(f4(f2(f3(2)))). But using console.log I see that the evaluation order is f2(f3(f4(f5(2)))) which is also 240 by coincidence.
As far as I understand the function y is called for all array elements so why only the last function gets 2 as the parameter?
Let's step through the code with a very simple example:
compose(f2, f3, f4)
As no initial value was passed to reduce, it will start with the first (f2) and the second (f3) value of the array and call the callback with that, x gets called with a being f2 and b being f3. Now x does'nt do anything, it just returns function y that can access a and b through a closure.
Reduce will now continue to the third element, the first argument being the result of the previous callback (the closured y), and the second argument being f4. Now x gets called again, and another closure is created over y, y gets the finally returned from the whole function.
If we try to visualize thus closured function it'll be:
y { // closure of y
a -> y { // a references another closure of y
a -> f3,
b -> f2
},
b -> f4
}
Now you call that closured y and pass 2 into it, that will call b (f4) and pass the result to the call to a (closured y).
a ( b(...args))
y { ... } ( f4(2) )
Now that closured y will do the same:
a ( b ( ...args))
f2( f3( f4( 2 ) ) )
Hint: It is sometimes really difficult to keep track of closured values, therefore the console provides you with great utilities to keep track of them: Open your code in the consoles "debugger" tab, click on the line numbers where the function calls are to attach breakpoints, then run the code again, the execution will yield whenever a breakpoint is reached and you can see the values of all variables (including closured ones).
The reduce is not calling the functions f2, f3, f3, f5, but it is creating a function from those. This is the value of the accumulator in each iteration. Note that the value is a function and not a result from execution of the function.
1:a=f2;b=f3;return value(NOT TEMP but function y)=f2(f3(...args))
2:a(prev return value)=f2(f3(...args));b=f4;return value=f2(f3(f4(...args)))
and so on....
The compose function can be re-written as:
function compose(...funcs) {
return funcs.reduce(function (a, b) {
return function (arg) {
const temp = a(b(arg));
return temp;
};
});
}
After the first iteration, the returned function which is passed in as the next accumulator is:
function (arg) { // R1
return f2(f3(arg));
}
After the second iteration, the returned function which is passed in as the next accumulator is:
function (arg) { // R2
return R1(f4(arg));
}
And finally, the returned function assigned to composedFunction is:
function (arg) { // composedFunction
return R2(f5(arg));
}
So running composedFunction(2) and going back up the chain:
f5(2) returns 10
R2(10) returns R1(f4(10))
which is R1(40)
R1(40) returns f2(f3(40))
which is f2(120)
which is 240
Hopefully that's sufficient.
It can be written as a single call as:
function composedFunction(arg) {
return f2(f3(f4(f5(arg))));
}
Can someone please explain the below 'Currying' function. When I set a break point, I can see values 'b' and 'c' are undefined and returned. But how does the system get the value 7 for 'b' and 9 for 'c' in this case. Its printing the correct result for 5*7*9, ie 315 in console.
function multiply(a){
return function (b){
return function (c) {
return a*b*c ;
}
}
}
var answer = multiply(5)(7)(9);
console.log(answer);
When you call multiply(5) a function is returned and that function is immediately called with multiply(5)(7) and have access to a and b, then a new function is returned and is also immediately called when multiply(5)(7)(9) and has access to a, b, and c.
The answer to why the nested functions have access to parent function parameters is closures. Please check this other question/answers about closures in javascript: link.
You can understand currying if you assign each intermediate result to a variable. Rewrite the function calls like this:
var x = multiply(5)
var y = x(7);
var answer = y(9);
Now it is more clear that the result of calling multiply(5) is a function. We call it with x(7) which passes the value of 7 to b. This results in another function which we call with y(9) which in turn passes the value of 9 to c and returns the final result.
When you call the multiply function, the important thing is each function returns an anonymous function. It will be easier if you give them names.
function multiplyA(a){
return function multiplyB(b){
return function multiplyC(c) {
return a*b*c ;
}
}
}
// When you call multiplyA(5)(7)(9)
// From the first, multiplyA(5) returns multiplyB with scope with multiplyA
// just like below
const a = 5;
const multiplyB = function(b){
return function multiplyC(c) {
return a*b*c ;
}
}
// Once more call multiplyB(7)
// It also returns function named multiplyC
const a = 5;
const b = 7;
const multiplyC = function(c) {
return a * b * c;
}
// Finally call mulitplyC(9) means 5 * 7 * 9
To understand it, closure and function scope will be helpful.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
I've just started to learn javascript and come across one task that I don't understand. Can anyone explain me why do we return function name "return f" in this example and what for do we use "f.toString"?
function sum(a) {
var currentSum = a;
function f(b) {
currentSum += b;
return f;
}
f.toString = function() {
return currentSum;
};
return f;
}
alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6
alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15
Lets start with a simplified version:
function sum(currentSum) {
return function f(b) {
currentSum += b;
return f;
}
}
It willwork much like yours, you can do:
sum(1)(2)(3);//f
sum(1)(2);//f
However, they always return a function, so were not able to access the currentSum. Its in sums scope and as its never returned or passed, its impossible to get it. So we probably need another function we can call to get the current sum:
function sum(currentSum) {
function f(b) {
currentSum += b;
return f;
}
f.getSum = function() {
return currentSum;
};
return f;
}
So now f has a property (functions are objects too), which is a function called getSum to get our variable
sum(1)(2)(3)//f
sum(1)(2)(3).getSum()//6 <= wohhooo
But why do we call it toString ?
When adding a variable to a string, its converted to a string, e.g.
1+"one"//"1one"
the same applies to objects/functions, but in this case, the js parser tries to call their toString method first, so:
sum(1)(2)+"three"
equals
sum(1)(2).toString()+"three"
the same conversion happens when passing non strings to alert.
You are returning the object. So you can call the function again and, in the second call, you will have a currentSum allready.
when you do sum(3) the function will hold the number 3 and when you call it again doing sum(3)(4) it will add 4 to the currentSum.
then the alert will call the toString method and it will print the sum
look at the first example
alert( sum(1)(2) ); // 3
sum(1) // will return f. sum must return a function in order for the syntax to work
after it will return f it will become:
alert( f(2) );
With function sum you are passing the first argument a and returning function f which sum currentSum with the argument passed to f (b) and return again f and you can do that many times you want at the end it will call alert function which needs its first argument to be string. For that purpose you have rewritten the method on function f toString which in this case will return the currentSum.
Every object has a toString() method that is automatically called when the object is to be represented as a text value.
This is the task for understanding the type system of JavaScript. The task is to make function that adds numbers using currying. The idea is to make function that adds numbers when called like this sum(1)(2)(3), as you written in the task.
What do we do (looking to your code) in function sum:
1.
var currentSum = a;
Here you declare a sum variable in scope of function sum.
function f(b) {
currentSum += b;
return f;
}
Then you declare the function that will perform summation. It returns itself for possibility of doing such thing: f(1)(2)(3)
3.
f.toString = function() {
return currentSum;
};
After that you declare that f, converted to string returns sum value
Than you return f to start adding.
Than what about f.toString - it 's being called, when f is passed alert as an argument. That's automatic casting of javascript
How does the second argument get called in liftf(add)(1)?
function add (first, second) {
return first + second;
}
function liftf (binary) {
return function (first) {
return function (second) {
return binary(first, second);
};
};
}
var inc = liftf(add)(1);
I understand how lift(add) is called and stored.
I am confused on how a function is returned but then called with (1).
I first explored if it operated on the same principle of an IIFE but it doesn't seem to. IFFE's would be (function() {}()) vs funciton() {}().
The 'chained' function arguments confuse me and I want to understand what's going on.
Thanks!
If an expression evaluates to a function, then that function can be invoked with parentheses and the list of arguments.
Since the expression liftf(add) returns a function, you call the returned function with the parameter 1 in parentheses: liftf(add)(1)
Another way to look at it is if you set liftf(add) to a variable, then you could call the function stored in that variable:
var additionFunc = liftf(add) // Stores the new function in additionFunc
var result = additionFunc(1) // Evaluates the new function
Let's also look at IIFEs. Suppose we have one like this:
(function(x) {return x + 1})(5)
The (function() { /* ... */ }) expression evaluates to a function, which is then evaluated by the parentheses and argument (5).
Let's look at a simpler example of currying:
function add(x) {
return function (y) {
return x + y;
};
}
If you called it with only one argument, like so:
add(2);
It would expand to:
function (y) {
return 2 + y;
}
Which would expect a y argument (if you called it). You could run that like this:
function (y) {
return 2 + y;
}(5)
Or more succintcly:
add(2)(5);
Each function just expands to a new anonymous function when currying, so even though it looks weird, once you expand the code out, it will start to make sense.
Assume I have a js function. From some other point in the program, I want to run its code, but not its return statement. In its place, I would like to run some other return statement that references the variables in the scope of the original function.
Is there a way to do this, other than loading up the function source, replacing the return, and using eval on the result? Minimal modification of the original is possible, though it should not affect the original's performance by adding e.g. an extra function call.
You could try something like this, but I'm not sure it meets your conditions.
Edit: Fixed to work in jsfiddle
// Modified to set all "shared" variables as "members" of the function.
var test = function() {
test.val = "one";
test.val2 = "two";
return 1;
}
// Using different result
function test2() {
test();
return test.val2;
}
Unless you're able to restructure your methods to accommodate a callback or introduce some other parameter-based logic-flow (not an option for 3rd party code), you're out of luck.
Here's a callback sample (fiddle, credit to dzejkej's answer)
function foo(callback) {
var x = 2;
// pass your values into the callback
return callback ? callback.call(this, x) : x * 2;
}
document.write(foo());
document.write("<hr/>");
// specify the parameters for your callback
document.write(foo(function(x){ return x * 4;}) );
You can introduce a callback function that will get called if available otherwise "standard" value will be returned.
function test(callback) {
// ...
return callback ? callback.call(this) : /* original value returned */ "xyz";
}
test(function() { /* "this" is same as in test() */ });
EDIT:
If you want to pass variables inside callback then you just list them in the .call() function.
Example:
function test(callback) {
var a = 4;
var b = 2;
// ...
return callback ? callback.call(this, a, b) : a * b;
}
test(); // 8
test(function(a, b) { return a + b; }); // 6
See this fiddle.
Provided that you would keep variables of the outer scope function within a single object, you could try something like the following:
function original(a, b, c, rep) {
var data = {};
// Do some fancy stuff but make sure to keep everything under data
data.a = a.replace(/foo/, 'bar');
...
if ( Object.prototype.toString.call(rep) === '[object Function]' )
return rep.call(data);
return data;
}
function replacement() {
return 'foo' + this.a;
}
// Now let's make use of both the original and the replacement ...
console.log(original('foo', x, y)); // => {a: "bar", b: ...}
console.log(original('foo', x, y, replacement)); // => {a: "foobar", b: ...}
Hope, it's what you where asking for.
cheers
I think you really misunderstand the concept of return statement. The return statement of a function will simply return a value, or an object, or undefined if there is no return parameter specified.
If all you're trying to do is execute a function but "not its return statement" than you would just invoke the function and not do anything with the returned value/object:
However, if what you mean is that you would like to execute a function but not execute the "parameter" to its return statement then that literally means to selectively execute an arbitrary portion of the body of a function. And as far as I know that is not possible (without using reflection to get the function definition, modify the definition, and then dynamically invoking the modified version - which you said you didn't want to do).