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));
Related
function executeActions(param)
{
if((param != undefined) && (param.length > 0))
{
for(i=0; i < param.length; i++)
{
//eval like function
param[i]();
}
}
}
function clearFields()
{
...
}
function showAbs(param)
{
if(param == 'insert')
{
...
}
else if(param == 'update')
{
...
}
else
{
...
}
}
$("#clearButton").click(function(event)
{
//var functions = ["clearFields()","showAbs('insert')"];
var a = showAbs('insert');
var functions = [clearFields, a];
executeActions(functions);
});
Hello everyone!
How can I execute some functions with parameters in a row in a set of instructions like i've showed above?
If they don't have any parameters, then the functions execute like in chain, but, if one or more of them uses
some parameters, it stops with the error: "param[i] is not a function".
Maybe if you have another elegant solution for this code, i'd appreciate if you share with us.
Thank you all in advance!
You can use partial application for this. Partial application means that you take a given function and fix one or more parameters to it. Example
function sum(a, b){
return a + b;
}
function product(a, b){
return a * b;
}
function doSomething(){
// do something
}
function runFunctions(funcs){
for(var i = 0;i<funcs.length;i++){
funcs[i]();
}
}
var mySum = function(){
return sum(5, 6);
}
var myProduct = function(){
return product(2, 3);
}
runFunctions(mySum, myProduct, doSomething);
The above is using ES 5 syntax. You could make this a bit more concise using ES 6 syntax:
const sum = (a, b) => a + b;
const product = (a, b) => a * b;
const doSomething = () => // do something
const runFunctions = funcs => {
for(func of funcs)
func();
}
var mySum = () => sum(5, 6);
var myProduct = () => product(2, 3);
runFunctions(mySum, myProduct, doSomething);
or you could use the bind function to take care of fixing the vars:
const sum = (a, b) => a + b;
const product = (a, b) => a * b;
const doSomething = () => // do something
const runFunctions = funcs => {
for(func of funcs)
func();
}
runFunctions(sum.bind(null, 5,6), myProduct.bind(null, 2,3), doSomething);
For me a way you want to achieve may be not readable for other developers.
You may create a function that will group all your function executions like:
function groupedFunctions{
return {
A: funcA(param),
B: funcB(param),
C: funcC(param)
}
}
function executeActions(funcObj, params) {
funcObj.A(params.a);
funcObj.B(params.b);
}
let params = {a: 1, b:2}
executeActions(groupedFunction(), params)
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); };
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)
When using bind in JS, one can create functions with predefined arguments, e. g.:
var add = function (a, b) {
return a + b;
};
var addToThree = add.bind(null, 3);
But how to I do this if I want to predefine the second, third etc. argument, but not the first?
In ES2015 you can do something like this:
const partial = fn => (...pargs) => (...args) => fn.apply(null, [...pargs, ...args]);
const partialRight = fn => (...pargs) => (...args) => fn.apply(null, [...args, ...pargs.reverse()]);
const myFunc = (one, two, three, four) => {
console.log(one);
console.log(two);
console.log(three);
console.log(four);
};
const myFuncPartial = partial(myFunc)('1');
const myFuncPartialRight = partialRight(myFuncPartial)('4', '3');
myFuncPartialRight('2');
You can do
var add = function (a, b) {
b = b || 5;
return a + b;
};
In ES6 Default Parameters can be used in a very easy way
var add = function (a, b=5) {
return a + b;
};
and call it like add(3);
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.