How to call this default args function more than once? - javascript

I have encountered a question where I need to allow default args to be set on a function in JavaScript:
function dfltArgs(func, params) {
const strFn = func.toString()
console.log(strFn)
const args = /\(([^)]+)\)/.exec(strFn)[1].split(',')
const defaultVal = (arg, val) => typeof arg !== 'undefined' ? arg : val
return (...dynamicArgs) => {
const withDefaults = args.map((arg, i) =>
defaultVal(dynamicArgs[i], params[args[i]]))
return func(...withDefaults)
}
}
function add (a, b) { return a + b }
var add_ = dfltArgs(add,{b:9})
console.log(add_(10)) // Should be 19
var add_ = dfltArgs(add_,{b:3})
console.log(add_(10)) // Should now be 13
However, I need to be able to call this function more than once and overwrite previously set defaults:
var add_ = defaults(add,{b:9})
add_(10) // Should be 19
var add_ = defaultArguments(add_,{b:3})
add_(10) // Should now be 13
This does not work in my implementation, because the stringified function on the second call is: (...dynamicArgs) => {, etc.
How can I refactor this? Probably need to use bind somehow?

Instead of your complicated default args thing, why not just use some arrow functions with real default arguments:
var _add = (a, b = 8) => add(a, b);
That way you can easily change the bound things:
var add_ = (a = 2, b) => _add(a, b);
add_() // 10

Related

How to create a composition from functions

I have 5 functions: func1(), func2(), func3(), func4(), func5(). I need to implement the compositionFunc() function, which can take any number of functions as arguments, and create a composition from them. The compositionFunc() function takes my 5 functions as arguments. The compositionFunc() function returns a function that takes its initial value as an argument. This nested function successively passing through an array of functions with each iteration returns the result of calling the accumulated value of the current function-argument. The result of one function can be passed as an argument to another function. How can i do this?
const func1 = (arg1) => {
return arg1;
};
const func2 = (arg2) => {
return arg2;
};
const func3 = (arg3) => {
return arg3;
};
const func4 = (arg4) => {
return arg4;
};
const func5 = (arg5) => {
return arg5;
};
const compositionFunc = () => {
...
};
you can define a function like this
const pipe = (...functions) => args => functions.reduce((res, f) => f(res), args)
const combine = (...functions) => args => functions.reduceRight((res, f) => f(res), args)
const plus1 = x => x + 1
const double = x => x * 2
const pipeFunction = pipe(plus1, double)
const combineFunction = combine(plus1, double)
console.log(combineFunction(1)) // (1 * 2) + 1
console.log(pipeFunction(1)) // (1 + 1) * 2
A simple reduce can accomplish that:
function pipe(input, ...func) {
return func.reduce((a, f) => f(a), input);
}
You pass it an initial value + chain of functions.
Example:
function f1(val) {
return val + 1;
}
function f2(val) {
return val * 10;
}
console.log(pipe(2, f1, f2)); //=> 30

passing argument to map function

I have code like:
var addX = (e) => return e+1;
I am calling like:
[1,2,3].map(addX);
Can I make "1" dynamic? Like:
[1,2,3].map(addX(2)); //this wont work, in this case it should add 2
You need a closure over e and return a function with one parameter for the callback.
var addX = x => v => x + v;
console.log([1, 2, 3].map(addX(2)));
You can use currying like this:
var addX = n => e => e + n;
console.log([1,2,3].map(addX(2)));
console.log([1,2,3].map(addX(10)));
What this does is, you pass the number (n) that you want to be added to the function and it returns a new function which adds that number to it's argument (e) (each element when using map)
You can use bind(thisArg, argument1) to send an extra parameter
var addX = (a, b) => a+b;
console.log("2", [1,2,3].map(addX.bind(Array, 2)))
console.log("5", [1,2,3].map(addX.bind(Array, 5)))
The this argument really does not matter in this case. I just put Array there, it can be this, null, etc.
You can create a function to return a function that takes your add amount.
Here is an example below.
var addX = (addbit) => (e) => e + addbit;
console.log([1,2,3].map(addX(2)));
I would do something like this :)
var addX = (e) => e+1;
[1,2,3].map(num => addX(num))
Several utility libraries like Lodash, Underscore, and Ramda provide a curry() utility function that takes a function and returns a new version of that function that can take the same arguments one at a time, a few at a time, or all at once.
This means that you can create an add function that can either add two numbers right away add(4, 5) or that can "pre-bake" a function with one of the values included: const increment = add(1); console.log(increment(5));
const add = _.curry((x, y) => x + y);
console.log(add(6, 7));
console.log([1,2,3].map(add(10)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
If you don't want to include a whole library just for this purpose, you can also use this standalone version of curry:
var curryN = (function () {
var slice = Function.prototype.call.bind(Array.prototype.slice);
var bindArr = function (f, arr) { return f.bind.apply(f, [{}].concat(arr)); };
return function curryN(argCount, func) {
return function fn() {
var args = slice(arguments, 0, argCount);
return args.length === argCount
? func.apply({}, args)
: bindArr(fn, args);
};
};
})();
var curry = function curry(func) { return curryN(func.length, func); };
const add = curry((x, y) => x + y);
console.log(add(6, 7));
console.log([1,2,3].map(add(10)));
You can use closure for that:
var addX = inc => e => e + inc;
var res = [1,2,3].map(addX(2));
console.log(res);
EXPLANATION
var addX = inc => e => e + inc;
Is the equivalent of:
var addX = function(inc) {
return function(e) {
return e + inc;
}
}
So addX(2) returns the callback function(e) { return e + 2 } and it's the callback used by array.map

JavaScript compose functions

I am reading a book which contains the following example:
var composition1 = function(f, g) {
return function(x) {
return f(g(x));
}
};
Then the author writes: "...naive implementation of composition, because it does not take the execution context into account..."
So the preferred function is that one:
var composition2 = function(f, g) {
return function() {
return f.call(this, g.apply(this, arguments));
}
};
Followed by an entire example:
var composition2 = function composition2(f, g) {
return function() {
return f.call(this, g.apply(this, arguments));
}
};
var addFour = function addFour(x) {
return x + 4;
};
var timesSeven = function timesSeven(x) {
return x * 7;
};
var addFourtimesSeven2 = composition2(timesSeven, addFour);
var result2 = addFourtimesSeven2(2);
console.log(result2);
Could someone please explain to me why the composition2 function is the preferred one (maybe with an example)?
EDIT:
In the meantime i have tried to use methods as arguments as suggested, but it did not work. The result was NaN:
var composition1 = function composition1(f, g) {
return function(x) {
return f(g(x));
};
};
var composition2 = function composition2(f, g) {
return function() {
return f.call(this, g.apply(this, arguments));
}
};
var addFour = {
myMethod: function addFour(x) {
return x + this.number;
},
number: 4
};
var timesSeven = {
myMethod: function timesSeven(x) {
return x * this.number;
},
number: 7
};
var addFourtimesSeven1 = composition1(timesSeven.myMethod, addFour.myMethod);
var result1 = addFourtimesSeven1(2);
console.log(result1);
var addFourtimesSeven2 = composition2(timesSeven.myMethod, addFour.myMethod);
var result2 = addFourtimesSeven2(2);
console.log(result2);
This just answers what composition2 actually does:
composition2 is used when you want to keep this as context in the functions itself. The following example shows that the result is 60 by using data.a and data.b:
'use strict';
var multiply = function(value) {
return value * this.a;
}
var add = function(value) {
return value + this.b;
}
var data = {
a: 10,
b: 4,
func: composition2(multiply, add)
};
var result = data.func(2);
// uses 'data' as 'this' inside the 'add' and 'multiply' functions
// (2 + 4) * 10 = 60
But yet, it still breaks the following example (unfortunately):
'use strict';
function Foo() {
this.a = 10;
this.b = 4;
}
Foo.prototype.multiply = function(value) {
return value * this.a;
};
Foo.prototype.add = function(value) {
return value + this.b;
};
var foo = new Foo();
var func = composition2(foo.multiply, foo.add);
var result = func(2); // Uncaught TypeError: Cannot read property 'b' of undefined
Because the context of composition2 (this) is undefined (and is not called in any other way, such as .apply, .call or obj.func()), you'd end up with this being undefined in the functions as well.
On the other hand, we can give it another context by using the following code:
'use strict';
var foo = new Foo();
var data = {
a: 20,
b: 8,
func: composition2(foo.multiply, foo.add)
}
var result = data.func(2);
// uses 'data' as 'this'
// (2 + 8) * 10 = 200 :)
Or by explicitly setting the context:
'use strict';
var multiply = function(value) {
return value * this.a;
};
var add = function(value) {
return value + this.b;
};
var a = 20;
var b = 8;
var func = composition2(multiply, add);
// All the same
var result1 = this.func(2);
var result2 = func.call(this, 2);
var result3 = func.apply(this, [2]);
composition1 would not pass arguments other than the first to g()
If you do:
var composition1 = function(f, g) {
return function(x1, x2, x3) {
return f(g(x1, x2, x3));
}
};
the function will work for the first three arguments. If you however want it to work for an arbitrary number, you need to use Function.prototype.apply.
f.call(...) is used to set this as shown in Caramiriel's answer.
I disagree with the author.
Think of the use-case for function-composition. Most of the time I utilize function-composition for transformer-functions (pure functions; argument(s) in, result out and this is irrelevant).
2nd. Utilizing arguments the way he does it leads into a bad practice/dead end, because it implies that the function g() might depend on multiple arguments.
That means, that the composition I create is not composable anymore, because it might not get all arguments it needs.
composition that prevents composition; fail
(And as a side-effect: passing the arguments-object to any other function is a performance no-go, because the JS-engine can't optimize this anymore)
Take a look at the topic of partial application, usually misreferenced as currying in JS, wich is basically: unless all arguments are passed, the function returns another function that takes the remaining args; until I have all my arguments I need to process them.
Then you should rethink the way you implement argument-order, because this works best when you define them as configs-first, data-last.Example:
//a transformer: value in, lowercased string out
var toLowerCase = function(str){
return String(str).toLowerCase();
}
//the original function expects 3 arguments,
//two configs and the data to process.
var replace = curry(function(needle, heystack, str){
return String(str).replace(needle, heystack);
});
//now I pass a partially applied function to map() that only
//needs the data to process; this is really composable
arr.map( replace(/\s[A-Z]/g, toLowerCase) );
//or I create another utility by only applying the first argument
var replaceWhitespaceWith = replace(/\s+/g);
//and pass the remaining configs later
arr.map( replaceWhitespaceWith("-") );
A slightly different approach is to create functions that are, by design, not intended to get all arguments passed in one step, but one by one (or in meaningful groups)
var prepend = a => b => String(a) + String(b); //one by one
var substr = (from, to) => value => String(str).substr(from, to); //or grouped
arr.map( compose( prepend("foo"), substr(0, 5) ) );
arr.map( compose( prepend("bar"), substr(5) ) );
//and the `to`-argument is undefined; by intent
I don't intend to ever call such functions with all the arguments, all I want to pass them is their configs, and to get a function that does the job on the passed data/value.
Instead of substr(0, 5, someString), I would always write someString.substr(0, 5), so why take any efforts to make the last argument (data) applyable in the first call?

Partial application right to left?

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);

how capture the arguments number need in a function (currying function partial application)

I am working on the curring function and partial application,
I am trying to improve the function schonfinkelize:
function schonfinkelize(fn){
var
slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
return function(){
var
new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
}
}
This function permit to pass as argument a function and a part of the argument of the function passed as argument (partial application) so the first time you return a function and then when you fire the function again the result.
function add(x, y, z){
return x + y + z;
}
var val = schonfinkelize(add, 1, 2);
console.log( val(3) ) // console output--> 6
I want check inside schonfinkelize the number of arguments need to the function "add" (but it should work with every function) so I can choose when return another function or directly the result of the function "add".
bacause if I use schonfinkelize in this way:
var val2 = schonfinkelize(add, 1, 2, 3);
console.log( val2 ) // --> function
console.log( val2() ) // --> 6
I have to fire the function two time, instead a want avoid this behavior and define directly the value if the arguments are sufficient.
A possible solution could be the following:
function schonfinkelize(fn){
var
slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
//* I have added this ********
if(fn.apply(null, stored_args))
return fn.apply(null, stored_args);
//****************************
return function(){
var
new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
}
}
Could be because it returns immediately the result if the fn.apply(null, stored_args) return something that is not "null" or "NaN" but I think is not really performant and then I want work with the arguments.
As long as you put in place a requirement that the parameters defined for the function passed reflect the actually number of arguments that are to be ultimately received, you can use the .length property of the function to do the comparison of passed arguments to anticipated arguments.
function schonfinkelize(fn) {
if (fn.length === arguments.length - 1)
return fn.apply(this, [].slice.call(arguments, 1));
var
slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
return function(){
var
new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
}
}
Side note... you can avoid the .slice() if you cache the fn in a new variable, and overwrite the first argument with the this value, then use .call.apply()...
if (fn.length === arguments.length - 1) {
var func = fn;
arguments[0] = this;
return func.call.apply(func, arguments);
}
In strict mode browsers you could even avoid having the make the new variable since the parameters are no longer mapped to changes in the arguments. But this doesn't work in browsers that don't support strict mode.
I don't think there is a correct way to determine number of arguments for arbitrary function. I prefer to store len in function if it is necessary, and check if it is defined, and if it is and if fn.len == stored_args.length then return function that just returns value.
function schonfinkelize(fn){
var
slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
if (fn.len != undefined && fn.len == stored_args.length) {
var val = fn.apply(null, stored_args);
return function () {
return val;
};
}
return function () {
var
new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
};
}
var f = function (a, b, c) {
return a + b + c;
};
f.len = 3;
var g = schonfinkelize(f, 1, 2);
alert(g); // function () { var new_args = slice.call(arguments), args = stored_args.concat(new_args); return fn.apply(null, args); };
alert(g(3)); // 6
var g = schonfinkelize(f, 1, 2, 3);
alert(g); // function () { return val; };
alert(g()); // 6
I want propose also a personal evolution of the code but I have to said thanks to squint to has resolved the problem, simply suggest me to use the property .length.
The next level it is in my opinion permit to create a partial function able to be called every time you want until you finish to fill all the arguments, I have also simplified the code:
function schonfinkelize(fn, stored_args){
if(fn.length == stored_args.length)
return fn.apply(null, stored_args);
return function(){
var
new_args = arguments[0],
args = stored_args.concat(new_args);
if(fn.length == args.length)
return fn.apply(null, args);
return schonfinkelize(fn, args);
}
}
function add(x, y, w, z){
return x + y + w + z;
}
var
val = schonfinkelize(add, [1, 2, 3, 4]),
val2 = schonfinkelize(add, [1, 2]),
val3 = schonfinkelize(add, [1]);
// checking
console.log(val); // output --> 10 // called only 1 time
console.log(val2([3, 4])); // output --> 10 // called in 2 times
val3 = val3([2]);
val3 = val3([3]);
console.log(val3([4])); // output --> 10 // called 4 times!

Categories