Wrapper function in Javascript - javascript

I understand wrapper would be something like
var str = 'Hello World'; // assigning string to a variable
console.log(str); // 'Hello World'
var str2 = new String('Hello World') // Creating a wrapper function
str2.valueOf() // 'Hello World'
By that logic, can the below example also be considered a wrapper function
function SuperOuterAdd(a, b){
console.log('Wrapper 2');
return OuterAdd(a, b);
}
function OuterAdd(a, b){
console.log('Wrapper 1');
return add(a, b);
}
function add(a, b){
return parseInt(a) + parseInt(b);
}

There's no language definition of wrapper function in JavaScript, and from your code, new String('Hello World'), is an instantiation of a string object - I don't see how that would be considered a wrapper function by any logic at all.
A wrapper function is a design concept where a very minimal function is using another function to do it's "work" for it, sometimes using a slightly different set of arguments.
for example:
function power(x, y) {
var res = 1;
while(y--) {
res *= x;
}
return res;
}
function square(x) {
return power(x, 2);
}
In the code above square is a wrapper function.

Wrappers are a loose term for a function that simply returns a value, with no computation. They are useful when we need a value, but not right away. Maybe the result is not ready yet when you define it, or you need some binding for the function to work (use of this).
Neither of the examples you provided is a wrapper function. The first one is simply an object instantiation (you're not even creating a function). It just so happens that the String constructor can take a string literal as an argument, which means it can work like the identity function. In the second, it's just some more elaborate contraption, but it's still function calling and computing things.
In general, wrapper functions are pretty useless out of context, and they're mostly a Javascript-specific thing, but consider the following:
let foo = null;
fetch('/my/api/call').then(function(res) {
foo = res;
getFoo(); // => [your object]
});
getFoo(); // => null
function getFoo() {
return foo;
}

Here is the example:
function SimpleWrapper() {
var self = this;
initialize();
function initialize() {
self.SuperOuterAdd = SuperOuterAdd;
self.OuterAdd = OuterAdd;
}
function SuperOuterAdd(a, b){
console.log('Wrapper 2');
return OuterAdd(a, b);
}
function OuterAdd(a, b){
console.log('Wrapper 1');
return _add(a, b);
}
function _add(a, b){
return parseInt(a) + parseInt(b);
}
}

Related

Returning a function with the arguments reversed

The code that I am practicing with is where I have a function called InReverse. This function accepts a function as an argument and returns a function. When the function returned is invoked, it reverses the order of the arguments.
When the returned functions are returned:
const catDog = ('cat', 'dog') => returns ('dog cat')
What I have rewritten out so far is:
function inReverse (func) {
return function (...arguments) {
return arguments.map((element) => {
element.reverse();
});
}
}
Any guidance would be appreciated!
You need to simply call the input function inside the newly created anonymous function.
For example this works:
function inReverse(f) {
return function () {
let args = [...arguments].reverse();
return f.apply(this, args);
}
}
So for example if you have subtract function like this:
function subtract(a, b) {
return a-b;
}
subtract(1, 10); will be -9 as expected.
and inReverse(subtract)(1, 10) will be 9 as expected.
Not sure why you're using map, just call reverse right on the arguments array. Also you weren't calling func:
function inReverse(func) {
return function(...args) {
return func(...args.reverse());
};
}
(Notice that arguments is a reserved identifier in strict mode, you should name your parameter for something else)
Not sure, why you are using map method, just use reverse method in your function right on the arguments. Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse?retiredLocale=id
Just reverse the arguments, and use func.apply(this, arr)
function inReverse(func) {
return function() {
var args = Array.prototype.slice.call(arguments)
args = args.reverse();
return func.apply(this, args);
}
}
function div(a, b) {
return a / b
}
console.log(div(1, 2))
console.log(inReverse(div)(1, 2))

What does the This keyword apply to in this Situation

I'm currently working on some exercises to get a deeper understanding of the 'this' keyword. It does seem to have a lot of use cases so I did read on MDN about 'this'. I'm wondering, what does the 'this' keyword in this exercise refer to? I know that when you use apply (which has a maximum of 2 arguments), your first argument is where you want the this 'keyword to be referenced to' and the second argument is an array to which the 'this' keyword is newly referenced to. where is return fn.apply(this,arguments); being referenced to and what is arguments in the second argument? Is it in the function, the window? Sorry, I'm just really confused and trying to wrap my head around it. This is the line of code that I'm confused about:
function add(a, b) {
return a + b;
}
function invokeMax(fn, num) {
var counter = 0;
return function() {
counter++;
if (counter > num) {
return 'Maxed Out!';
}
return fn.apply(this, arguments);
};
}
You can console.log() this in the returned function and find out. Here, you will see it points to the global object (or window in a browser). This code doesn't depend on this being anything in particular. You could rewrite it as:
return fn.apply(null, arguments);
and get the same result.
this is determined by the way functions are called. The function here returns a function that (presumably) you will just call by itself, so the only calling's context is the window:
function add(a, b) {
return a + b;
}
function invokeMax(fn, num) {
var counter = 0;
return function() {
counter++;
if (counter > num) {
return 'Maxed Out!';
}
console.log("this is window?", this === window)
return fn.apply(this, arguments);
};
}
let f = invokeMax(add, 2)
console.log(f(5, 6))
Calling the same function in a different context leads to a different value of this:
function add(a, b) {
return a + b;
}
function invokeMax(fn, num) {
var counter = 0;
return function() {
counter++;
if (counter > num) {
return 'Maxed Out!';
}
console.log("this: ", this)
return fn.apply(this, arguments);
};
}
let someObj = {name: "myObj"}
someObj.f = invokeMax(add, 2) // now this will be someObj
someObj.f()
EDIT based on comment
A basic apply() example. The function will use the object passed to the first parameter of apply() as this in the function:
function print(someArg){
console.log(this.myName, someArg)
}
print.apply({myName: "Mark"}, ["hello"]) // set this to the passed in object
print.apply({myName: "Teddy"}, ["hello"]) // set this to the passed in object
print("hello") // called normally `this` will be the widow which doesn't have a `myName` prop.
// but you can give window that property (but probably shouldn't)
window.myName = "I'm window"
print("hello")
In that instance this refers to the current scope, which is the function where this is contained. In JavaScript, functions are also objects that can have properties assigned to them.

Why does returning this ECMAScript Harmony arrow function expression produce unexpected behavior?

I've been playing with the new ECMAScript 6 features and this question has to do with arrow functions. The following code is a simple functional composition method assigned to the Function object's prototype. It works perfectly well using a simple anonymous function but does not when using an arrow function instead.
Function.prototype.compose = function (bar) {
var foo = this;
return function () {
return foo(bar.apply(null, arguments));
};
};
var addFive = function (baz) {
return baz + 5;
};
var addTen = function (hello) {
return hello + 10;
};
var addFifteen = addFive.compose(addTen);
console.log(addFifteen(10));
http://jsfiddle.net/oegonbmn/
Function.prototype.compose = function (bar) {
var foo = this;
return () => foo(bar.apply(null, arguments));
};
var addFive = function (baz) {
return baz + 5;
};
var addTen = function (hello) {
return hello + 10;
};
var addFifteen = addFive.compose(addTen);
console.log(addFifteen(10));
http://www.es6fiddle.com/hyo32b2p/
The first one logs 25 correctly to the console whereas the second one logs function (hello) { return hello + 10; }105 which doesn't exactly tell me what I'm doing wrong.
I am not returning the value within the arrow function since it is supposed to implicitly return the very last statement (the first and last in this instance) and I suppose the issue at hand has something to do with the lexical scoping and the values of this, maybe. Can anyone explain?
Both this and arguments are not (re)bound in arrow functions, but instead lexically scoped. That is, you get whatever they are bound to in the surrounding scope.
In ES6, using arguments is deprecated anyway. The preferred solution is to use rest parameters:
Function.prototype.compose = function (bar) {
return (...args) => this(bar.apply(null, args));
};
or, in fact:
Function.prototype.compose = function (bar) {
return (...args) => this(bar(...args));
};

I'm reading Eloquent Javascript and I am a little confused by this partial function example. Please help explain

function asArray(quasiArray, start) {
var result = [];
for (var i = (start || 0); i < quasiArray.length; i++)
result.push(quasiArray[i]);
return result;
}
function partial(func) {
var fixedArgs = asArray(arguments, 1);
return function(){
return func.apply(null, fixedArgs.concat(asArray(arguments)));
};
}
function compose(func1, func2) {
return function() {
return func1(func2.apply(null, arguments));
};
}
var isUndefined = partial(op["==="], undefined);
var isDefined = compose(op["!"], isUndefined);
show(isDefined(Math.PI));
show(isDefined(Math.PIE));
Why can't the function compose simply return:
func1(func2);
and give the proper output. I thought the partial function which is stored in the variable isUndefined already returns func.apply(null, [fixed, arguments])
var op = {
"+": function(a, b){return a + b;},
"==": function(a, b){return a == b;},
"===": function(a, b){return a === b;},
"!": function(a){return !a;}
/* and so on */
};
Both partial and compose are higher-order functions.
isUndefined will return a function that, when invoked, will invoke the originally passed function with the original arguments plus any new arguments passed at invocation.
To answer your question, you'd be calling apply on the function returned from partial which will in turn, call apply on the function originally passed to partial.
You want compose to return a function that when called, will return the result of calling the first function passed the second function as an argument (with the second function passed the arguments passed to the compose invocation). If compose returned func1(func2), then you'd assign the result of the invocation to the variable isDefined.
EDIT:
Now that we have op, let's try to decompose this:
var isUndefined = partial(op["==="], undefined);
this is equivalent to
var isUndefined = partial(function(a, b){return a === b;}, undefined);
isUndefined is assigned a function that, when called, will call the function passed as the first argument to partial, passing in undefined as the first argument to that function call, followed by the arguments passed to the function isUndefined i.e.
partial(function(a, b){return a === b;}, undefined /* this will become 'a' when isUndefined is invoked */)(argumentForisUndefined /* this will become 'b' when isUndefined is invoked */);
isDefined composes isUndefined with another function that negates the result of isUndefined.
var isDefined = compose(op["!"], isUndefined);
is equivalent to
var isDefined = compose(function(a){return !a;}, isUndefined);
which is equivalent to (renamed variables for clarity)
var isDefined = compose(
function(a){return !a;},
partial( /* partial function becomes 'a' passed to first function */
function(b, c) {
return b === c;
},
undefined /* undefined becomes 'b' passed to partial */
)
)(argumentForisDefined /* argumentForisDefined becomes 'c' passed to partial */);
If we look at what we have so far and substituting for readability, boils down to a function that takes an argument and compares it to undefined, negates the result and returns a boolean
var isDefined = function (b) { return !undefined === b; }
So lets simply dissect it. Assuming we have this compose function:
function compose(func1, func2) {
return func1(func2.apply(null, arguments));
}
What will happen when you use it like this?
a = compose(function(){console.log(1)}, function(){console.log(2)});
The second function would be call immediately outputting 2, and straight afterwards the first function will be called outputting 1. a will be undefined, because the first function does not return anything.
What you want combine to do, is to return a new function, that combines the two other functions and that you can call at will.
Doing the above all on the original compose, will return a new function, that, when you call it with a() will output 2 and then 1.

how to use function(1)(2) in javascript? and how does it work?

I understand calling function(1) but not function(1)(2), how does it work?
also possible for function(1)(2)(3)(4) too?
In this case you are supposing that function(1) returns a function, than you are calling this new, anonymous function with an argument of 2.
See this example:
function sum(a) {
return function(b) {
return a+b;
}
}
// Usage:
window.alert(sum(5)(3)); // shows 8
var add2 = sum(2);
window.alert(add2(5)); // shows 7
window.alert(typeof(add2)); // shows 'function'
Here we create a function sum that takes one argument. Inside the function sum, we create an anonymous function that takes another argument. This anonymous function is returned as the result of executing sum.
Note that this anonymous function is a great example of what we call closure. A closure is a function that keeps the context in which it was created. In this case, it will keep the value of the variable a inside it, as did the example function add2. If we create many closures, they are independent as you can see:
var add3 = sum(3);
var add4 = sum(4);
window.alert(add3(3)); // shows 6
window.alert(add4(3)); // shows 7
Furthermore, they won't get "confused" if you have similarly named local variables:
var a = "Hello, world";
function multiply(a) {
return function(b) {
return a * b;
}
}
window.alert(multiply(6)(7)); // shows 42
var twoTimes = multiply(2);
window.alert(typeof(twoTimes));
window.alert(twoTimes(5));
So, after a call to sum(2) or multiply(2) the result is not a number, nor a string, but is a function. This is a characteristic of functional languages -- languages in which functions can be passed as parameters and returned as results of other functions.
You have a function that returns a function:
function f(n) {
return function(x) {
return n + x;
};
}
When you call f(1) you get a reference to a function back. You can either store the reference in a variable and call it:
var fx = f(1);
var result = fx(2);
Or you can call it directly:
var result = f(1)(2);
To get a function that returns a function that returns a function that returns a function, you just have to repeat the process:
function f(n) {
return function(x) {
return function(y) {
return function(z) {
return n + x + y + z;
}
}
};
}
If your function returns a function, you can call that too.
x = f(1)(2)
is equivalent to:
f2 = f(1)
x = f2(2)
The parenthesis indicate invocation of a function (you "call" it). If you have
<anything>()
It means that the value of anything is a callable value. Imagine the following function:
function add(n1) {
return function add_second(n2) {
return n1+n2
}
}
You can then invoke it as add(1)(2) which would equal 3. You can naturally extend this as much as you want.

Categories