I found this code in a book, how do you write or define the code for mybind
var concat = function(a, b) { return a + " " + b;}
var good = mybind(concat, "good");
good("night") == "good night"
To create a new function, you can either create it yourself:
function mybind(f, a) {
return function (b) {
return f(a, b);
}
}
var concat = function(a, b) { return a + " " + b;}
var good = mybind(concat, "good");
console.log(good("night"));
or for your scenario you can use function.bind to create one for you
function mybind(f, a) {
return f.bind(null, a);
}
var concat = function(a, b) { return a + " " + b;}
var good = mybind(concat, "good");
console.log(good("night"));
Like this:
var concat = function(a, b) { return a + " " + b;}
var mybind = function (fn, arg1) {
return function (arg2) {
return fn(arg1, arg2);
};
}
var good = mybind(concat, "good");
console.log(good("night") === "good night")
The following will make your comparison return true. myBind should create a new function bound to b. that's what bind does.
var mybind = function( fn, b ) { return fn.bind(this, b); };
Related
I'm troubleshooting some 3rd party code on a client's website. The client was having issues with the code not working. I found that the issue was related to bound JS functions. Arguments that were passed to the bound function were undefined. I couldn't figure out why. Everything seems fine. However, I then found that the client has overridden the Bind function. Here is what they have:
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
};
};
So if I create a function
var sumFunction = function(a, b){
console.log("a: " + a);
console.log("b: " + b);
return a + b;
}
Then bind that function:
var boundFunction = sumFunction.bind(null, 10);
When I call that bound function I get the following:
console.log(boundFunction(20));
a: 20
b: undefined
NaN
I found a similar SO question that was using the same bind function. javascript custom scope binding function
It appears that it used to work? The SO question I linked seemed to work back in 2013, but now it doesn't form me.
Is this just outdated? JavaScript isn't my main strength, but my client will want to know why their function is causing the problem.
I found the overridden bind function to be odd. Especially the line return _function.apply(scope, arguments); It seems like passing the entire arguments object is incorrect. Shouldn't it only send the arguments in array position 1 and higher? I tried changing that to this to test:
Function.prototype.bind = function(scope) {
var _function = this;
var newArgs = Array.prototype.slice.call(arguments, 1)
return function() {
return _function.apply(scope, newArgs );
};
};
But now I just get the following:
console.log(boundFunction(20));
a: 10
b: undefined
NaN
When the function is bounded, there might be an array of arguments after the 1st, so use slice(1) to get them. When the function is called, get the all the arguments, and concat both args arrays.
Concat both arrays of arguments:
Function.prototype.bind = function(scope) {
var _function = this;
var args1 = Array.prototype.slice.call(arguments, 1);
return function() {
var args2 = Array.prototype.slice.call(arguments, 0);
return _function.apply(scope, args1.concat(args2));
};
};
var sumFunction = function(a, b){
console.log("a: " + a);
console.log("b: " + b);
return a + b;
}
var boundFunction = sumFunction.bind(null, 10);
console.log(boundFunction(20));
However, calling slice on arguments, might cause the V8 engine to skip optimisation on the function. A better way would be to just iterate the arguments manually, and add them to a single array:
Function.prototype.bind = function(scope) {
var args = [];
var _function = this;
for(var i = 1; i < arguments.length; i++) { args.push(arguments[i]); }
return function() {
var newArgs = args.slice(0);
for(var i = 0; i < arguments.length; i++) { newArgs.push(arguments[i]); }
return _function.apply(scope, newArgs);
};
};
var sumFunction = function(a, b){
console.log("a: " + a);
console.log("b: " + b);
return a + b;
}
var boundFunction = sumFunction.bind(null, 10);
console.log(boundFunction(20));
I have tried writing the below code to find sum of 'n' numbers using sum function. I am getting the correct response in output. But i am unable to return that using sum function, as i always have to return a function, which is required for curried effect.
Please help. Thanks in advance.
var output = 0,
chain;
function sum() {
var args = Array.prototype.slice.call(arguments);
output += args.reduce(function(a, b) {
return a + b;
});
sumCurried = sum.bind(output);
sumCurried.val = function() {
return output;
}
return sumCurried;
}
debugger;
document.getElementById('demo').innerHTML = sum(1, 2)(3)(4);
// document.getElementById('demo').innerHTML = sum(1)(3)(4);
<p id='demo'></p>
enter code here
You can add a stop condition to the curried function, for example - if the function is called without an argument return the output:
var output = 0,
chain;
function sum() {
var args = Array.prototype.slice.call(arguments);
if(args.length === 0) {
return output;
}
output += args.reduce(function(a, b) {
return a + b;
});
sumCurried = sum.bind(output);
return sumCurried;
}
console.log(sum(1, 2)(3)(4)());
<p id='demo'></p>
The returned curry function has a val property, which is a function that returns the current value:
var output = 0,
chain;
function sum() {
var args = Array.prototype.slice.call(arguments);
output += args.reduce(function(a, b) {
return a + b;
});
sumCurried = sum.bind(output);
sumCurried.val = function() {
return output;
}
return sumCurried;
}
console.log(sum(1, 2)(3)(4).val());
<p id='demo'></p>
Why would you use currying at all? However, here is a shorter version:
const sum = (...args) => {
const func = (...s)=> sum(...args,...s);
func.value = args.reduce((a,b)=>a+b,0);
return func;
};
//usable as
sum(1,2).value,
sum(1,1)(1).value,
sum(1,1)(1,1)(1,1).value
And you always need to end the currying chain. However, it can be shortified:
func.valueOf = ()=> args.reduce((a,b)=>a+b,0);
//( instead of func.value = ... )
So when called you can do:
+sum(1,2,3)
+sum(1)(1)(1)
var add = function(a, b) {
return a + b;
}
var addOne =add.bind(null,1);
var result = addOne(4);
console.log(result);
Here the binded value of a is 1 and b is 4.
How to assign the binding value i.e)1 to the second argument of the function without using spread operator(...)
You could take a swap function with binding the final function.
var add = function (a, b) { console.log(a, b); return a + b; },
swap = function (a, b) { return this(b, a); },
addOne = swap.bind(add, 1),
result = addOne(4);
console.log(result);
With decorator, as georg suggested.
var add = function (a, b) { console.log(a, b); return a + b; },
swap = function (f) { return function (b, a) { return f.call(this, a, b) }; },
addOne = swap(add).bind(null, 1),
result = addOne(4);
console.log(result);
You could use the arguments object for reordering the parameters.
var add = function (a, b, c, d, e) {
console.log(a, b, c, d, e);
return a + b + c + d + e;
},
swap = function (f) {
return function () {
var arg = Array.apply(null, arguments);
return f.apply(this, [arg.pop()].concat(arg));
};
},
four = swap(add).bind(null, 2, 3, 4, 5),
result = four(1);
console.log(result);
You can use the following way
var add = function(x){
return function(y){
return x+y;
}
}
add(2)(3); // gives 5
var add5 = add(5);
add5(10); // gives 15
here add5() would set x = 5 for the function
This will help you what you need
var add = function(a) {
return function(b) {
return a + b;
};
}
var addOne = add(1);
var result = addOne(4);
console.log(result);
You can try this
function add (n) {
var func = function (x) {
if(typeof x==="undefined"){
x=0;
}
return add (n + x);
};
func.valueOf = func.toString = function () {
return n;
};
return func;
}
console.log(+add(1)(2));
console.log(+add(1)(2)(3));
console.log(+add(1)(2)(5)(8));
My code looks like this:
function x(a,b)
{
return a + b;
}
var f = x;
function x(a,b)
{
return a - b;
}
var res = f(2,1);
I expect that the result is 3 as f is pointing to function x before modifying it, but it isn't the case, how can I keep a reference to a function that is foing to be redefined?
Function declarations are processed before expressions. Therefore, from the point of view of the interpreter, your code is interpreted as this:
function x(a,b)
{
return a + b;
}
function x(a,b)
{
return a - b;
}
var f = x;
var res = f(2,1);
The solution is to re-assign the function using a function expression instead of a function declaration. This is because as I mentioned above expressions are processed after declarations:
function x(a,b)
{
return a + b;
}
var f = x;
x = function (a,b) // <--------- this fixes your problem
{
return a - b;
}
var res = f(2,1);
Note, that since declarations are processed before expressions, the following would work as well:
var f = x;
x = function (a,b)
{
return a - b;
}
var res = f(2,1);
function x(a,b) // this is processed first
{
return a + b;
}
Functions and variable declarations (but not variable assignments) are "hoisted" to the top of their containing scope.
So your code is equivalent to this:
function x(a,b) {
return a + b;
}
function x(a,b) { //this overwrites the previous function declaration
return a - b;
}
var f;
var res;
f = x;
res = f(2,1); //1
It should now be clear why f(2,1) is 1 instead of 2.
You can overcome this by creating functions as variables instead:
var x = function(a, b) {
return a + b;
}
var f = x;
console.log(f(2, 1)); //3
var x = function(a, b) {
return a - b;
}
var f = x;
console.log(f(2, 1)); //1
Assign your functions to variables when creating them:
var f1 = function(a, b) {
return a + b;
}
var f2 = f1;
f1 = function(a, b) {
return a - b;
}
alert( f1(2,1) ); // < Will subtract
alert( f2(2,1) ); // < Will add
This allows you to easily clone the function.
I try to use in my app, simple comparator to filter some data with passing string filter instead function as eg. passed to [].filter
Comparator should return function which will be a filter.
var comparator = function( a, b, c ) {
switch( b ){
case '>=': return function() { return this[a] >= c;}; break;
case '<=': return function() { return this[a] <= c;}; break;
case '<': return function() { return this[a] < c;}; break;
case '>': return function() { return this[a] > c;}; break;
case '=': return function() { return this[a] == c;}; break;
case '==': return function() { return this[a] === c;}; break;
case '!=': return function() { return this[a] != c;}; break;
default: return null;
};
}
Assume that i get this function by:
var filterFn = comparator.apply({}, /(.+)(=|>=|<=|<|>|!=|==|!==)(.+)/.exec( "id<4" ).slice(1) );
someModel = someModel.objects.filter( filterFn );
The target it will look:
someModel.get = function( filter ){
return new Model(
this.objects.filter(
comparator.apply({}, /(.+)(=|>=|<=|<|>|!=|==|!==)(.+)/.exec( "id<4" ).slice(1)
)
);
};
var filtered = someModel.get( "id<4" );
Question is - I assume that it will be a lot more operators and I have no idea how to write it more simply.
Using Eval is out of question.
This code didn't was both executed and tested I wrote it just to show what I mean.
Store every function in an object, either pre-defined, or dynamically.
If you want to dyanmically create the set of functions, define the comparator object as shown below. I assumed that you did not extend the Object.prototype. If you did, operators.hasOwnProperty(property) has to be used within the first loop.
// Run only once
var funcs = {}; // Optionally, remove `funcs` and swap `funcs` with `operators`
var operators = { // at the first loop.
'>=': '>=',
'<=': '<=',
'<' : '<',
'>' : '>',
'=' : '==', //!!
'==':'===', //!!
'!=': '!='
}; // Operators
// Function constructor used only once, for construction
for (var operator in operators) {
funcs[operator] = Function('a', 'c',
'return function() {return this[a] ' + operator + ' c};');
}
// Run later
var comparator = function(a, b, c) {
return typeof funcs[b] === 'function' ? funcs[b](a, c) : null;
};
When comparator is invoked, the returned function looks like:
function() { return this[a] < c; }// Where a, c are pre-determined.
This method can be implemented in this way (demo at JSFiddle):
// Assumed that funcs has been defined
function implementComparator(set, key, operator, value) {
var comparator, newset = [], i;
if (typeof funcs[operator] === 'function') {
comparator = funcs[operator](key, value);
} else { //If the function does not exist...
throw TypeError("Unrecognised operator");
}
// Walk through the whole set
for (i = 0; i < set.length; i++) {
// Invoke the comparator, setting `this` to `set[i]`. If true, push item
if (comparator.call(set[i])) {
newset.push(set[i]);
}
}
return newset;
}
var set = [ {meow: 5}, {meow: 3}, {meow: 4}, {meow: 0}, {meow: 9}]
implementComparator( set , 'meow', '<=', 5);
// equals: [ {meow: 5}, {meow: 3}, {meow: 4}, {meow: 0} ]
For clarification, I constructed this answer, while keeping the following in mind:
The OP requests an simple, easily extensible method with an unknown/dynamic set of operators.
The code is based on the pseudo-code at the OP, without changing anything which could affect the intent of the OP. With some adjustments, this function can also be used for Array.prototype.filter or Array.prototype.sort.
eval (or Function) should not be used at every call to comparator
Don't do it so dynamically....it would be far more efficient to only create the functions once, rather than each time they are called, as that would create a new funciton and so a memory leak each time the compare is done.
var comparator = {
">=": function(a, b) { return a >= b;},
"<=": function(a, b) { return a <= b;},
"add": function(a, b) { return a + b; },
compare: function(typeString, a, b){
if(comparator.hasOwnProperty(typeString) == true){
var theFunction = comparator[typeString];
return theFunction(a, b);
}
else{
alert("typeString '" + typeString + "' not supported.");
}
}, };
var test = comparator.compare(">=", 5, 4);
var comparator = (function () {
var fns = {
'>=': function (a, c) { return a >= c; },
'<=': function (a, c) { return a <= c; },
'<': function (a, c) { return a < c; },
'>': function (a, c) { return a > c; },
'=': function (a, c) { return a == c; },
'==': function (a, c) { return a === c; },
'!=': function (a, c) { return a != c; }
};
return function (b) {
return fns.hasOwnProperty(b) ? fns[b] : null;
};
}());
At this point you can see that nothing is more efficient than an inline expression. It is not clear to me why you think you need to be so dynamic beforehand.