javascript function that takes parameter in different format - javascript

Recently i have been asked to write a javascript function (it was a coding test) where they wanted me to implement a function which will add and return the values.
add(3,2);//should return 5
add(3)(2); //should return 5
I am not sure whether this is possible at all. I am not an expert in javascript so could get any clue from google search.

You would have to check whether the second argument was given first; if so, return the result immediately; otherwise, return a function that will complete the addition:
function add(a, b)
{
if (typeof b == 'undefined') {
return function(b) {
return a + b;
}
} else {
return a + b;
}
}
Alternatively, if you don't like the duplicate logic:
function add(a, b)
{
var f = function(b) {
return a + b;
};
return typeof b == 'undefined' ? f : f(b);
}
This is also referred to as partial function application or currying.

Solution For add(x,y):
function add(x, y) {
return x + y
}
Solution For add(x)(y):
function add(x) {
return function(y){
return x+y;
}
}

Related

Function that takes a number as an argument and returns a boolean javascript

I am new to coding and I have this exercise where I have to write a function that takes a number as argument and returns a boolean. This is the code I wrote but is not working and I am getting the warning
"The function should only have a return statement in its body. You can evaluate a boolean expression an return immediately its value"
var even = function(x) {
if ((x % 2) === 0) {
return true;
} else
return false;
};
The response you get from the code submission has an important point:
The expression (x%2)===0 is already a boolean, so you can return that expression:
return x%2 === 0;
In general you should avoid this pattern:
if (some_boolean_expression) {
return true;
} else {
return false;
}
... since the boolean you return is exactly the same as the boolean expression that is evaluated in the if condition. So it should be just:
return some_boolean_expression;
you can just write your function like this
var even = function(x)
{
return x % 2 === 0
}
var even = function(x) {
if (typeof x === "number") {
if (x % 2 === 0) {
return true
} else {
return false
}
} else {
return false
}
}
This covers all the edge cases

Trying to make a repeater function using only higher order functions?

I'm trying to make a function that accepts another function and outputs that function repeatedly by only using function expressions/applications.
So far I have a function twice which accepts another function as an argument and returns func(func(x)):
function twice(func) {
function x(x) {
return func(func(x));
}
return x;
}
I'm trying to make a repeater function such that const thrice = repeater(twice) returns func(func(func(x))), and const fourtimes = repeater(thrice) etc. but i'm confused as to how to do this. Any help would be appreciated greatly. Thank you
Using your current structure thats impossible as twice does not expose a reference to func, thus repeater cannot call it.
The only solution I could think of would be to leak func from the inside through a (hidden) property:
const r = Symbol();
const repeater = f => Object.assign(
v => f[r] ? f(f[r](v)): f(v),
{ [r]: f[r] || f }
);
const addThree = repeater(repeater(repeater(n => n + 1)));
console.log(addThree(10));
You should two base cases (if n == 0 => exit, if n == 1 => return f(x)), where n is an additional parameter that specifies how many times the function should repeat with the arguments args:
function repeater(func, x, n) {
if (n == 0) return;
if (n == 1) return func(x);
else {
return func(repeater(func, x, --n));
}
}
let sqr = n => n * n;
console.log(repeater(sqr, 2, 3));
Do you look for something like this?
function chain(f, g) {
return function (x) {
return f(g(x));
}
}
function ntimes(f, n) {
if (n == 0) {
return function (x) { return x }
} else {
return chain(f, ntimes(f, n-1));
}
}
This will make a new function which repeats the original function f n times.

How can this chaining be achieved in Javascript? [duplicate]

This question already has an answer here:
Writing a function f which would satisfy the following test
(1 answer)
Closed 3 years ago.
f()()('x') // foox
f()()()()('x') //foooox
I tried to return nested functions but unable to get desired result.
You can create a function that returns function or result based on passed argument assuming that only last call have an argument passed.
function f() {
let os = ''
return function again(x) {
os += 'o'
if (!x) return again;
else return `f${os}${x}`;
}
}
console.log(f()()('x'))
console.log(f()()()()('x'))
console.log(f()()()()()()('Y'))
Just use a counter variable and return a function if the variable is not defined.
const f = (a, c = 0) => a ? "f" + "o".repeat(c) + a : b => f(b, ++c);
console.log(f()()("x"));
console.log(f()()()()("z"));
ES5 syntax:
function f(a, c) {
c = c || 0;
if (a) {
return "f" + "o".repeat(c) + a;
} else {
return function(b) {
return f(b, c + 1);
}
}
}
console.log(f()()("x"));
console.log(f()()()()("z"));
You could return a function for more than one call of the function and implement a toString method to get the final string.
function f(v = 'o') {
var s = 'f' + v;
function g(v = 'o') {
s += v;
return g;
};
g.toString = function () { return s; };
return g;
}
console.log(f()()); // foo
console.log(f('it')); // fit
console.log(f()('x')); // fox
console.log(f()()('b')('a')('r')); // foobar

pass one value less to function i see a mismatch and returns NAN

Why is this function returning NaN?
function add(a, b) {
return a + b;
}
//add(10);
var result = add(10);
console.log(result);
b is undefined when you only pass 10 to the function, thus 10 + undefined is what you're returning; so NaN, aka Not a Number.
The problem here is that b is undefined. Therefore, in your addition, JavaScript tries to coerce undefined to a number. The result of this coercion is always NaN:
console.log(+undefined);
console.log(parseInt(undefined));
console.log(Number(undefined));
And of course, a number + NaN always gives you NaN:
console.log(1 + NaN);
console.log(NaN + 1);
If you want to restrict this permissive behavior of JavaScript, you could use default parameters and/or throw custom errors:
function add(a, b) {
a = a || 0;
b = b || 0;
return a + b;
}
var result = add(10);
console.log(result);
function add(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
if (isNaN(a) || isNaN(b)) {
throw new Error('NaN is not a number');
} else {
return a + b;
}
} else {
throw new Error('Invalid operands');
}
}
var result = add(10);
console.log(result);
Currying could also be considered:
function add(a) {
return function (b) {
return a + b;
};
}
console.log(add(10));
console.log(add(10)(3));
function add(a, b) {
return a + b;
}
//add(10);
var result = add(10,0);
//change this
console.log(result);

How do you curry any javascript function of arbitrary arity?

Let's say I have some function:
function g(a,b,c){ return a + b + c }
And I'd like to turn it into its "curried" form (in quotations since it's not exactly curried per se):
function h(a,b,c){
switch(true){
case (a !== undefined && b !== undefined && c !== undefined):
return a + b + c
case (a !== undefined && b !== undefined && c === undefined):
return function(c){ return a + b + c }
case (a !== undefined && b == undefined && c === undefined ):
return function(b,c){
return (c === undefined) ? function(c){ return a + b + c } : a + b + c
}
default:
return h
}
}
The above form has the partial binding behavior I want:
h(1) -> h(b,c)
h(1,2) -> h(c)
h(1,2,3) -> 6
h() -> h(a,b,c)
Now I'd like to automate this process into some generic function curry such that given any un-curried function (and maybe its number of parameters), the above function is generated. But I'm not quite sure how to implement it.
Alternatively, if the following form could be automatically created, it'd be also interesting:
function f(a,b,c){
return function(a){ return function(b){ return function(c){ return a + b + c }}}
}
Though binding f looks like this:
f(1)(2)(3) = 6
so it is very unwieldily and non-idiomatic, but creating the above form seem more feasible to me.
Now is could any of the above form be generated by some function, if so, how?
I believe that you could simply use Function.prototype.bind. That gives you all the flexibility you need, wheter you want the result of the function right away or simply push another value into the arguments until you decide to execute.
function sum() {
return [].reduce.call(arguments, function (c, n) {
return c + n;
});
}
sum(1, 2); //3
var sum2 = sum.bind(null, 1, 2);
sum2(); //3
var sum3 = sum2.bind(null, 3);
sum3(); //6
You could also use a helper function like:
function curry(fn) {
var c = curry.bind(this, fn = fn.bind.apply(fn, [this].concat([].slice.call(arguments, 1))));
c.exec = fn;
return c;
}
curry(sum, 1, 2)(3)(4, 5)(6, 7, 8).exec(); //36
Also this is very flexible as you do not have to chain, you can re-use the same curried function.
var sumOnePlus = curry(sum, 1);
sumOnePlus.exec(2); //3;
sumOnePlus.exec(3); //4;
Here's my attempt:
function curry(fn, len) {
if (typeof len != "number")
len = fn.length; // getting arity from function
return function curried() {
var rlen = len - arguments.length;
if (rlen <= 0) // then execute now
return fn.apply(this, arguments);
// else create curried, partially bound function:
var bargs = [this]; // arguments for `bind`
bargs.push.apply(bargs, arguments);
return curry(fn.bind.apply(fn, bargs), rlen);
};
}
This does not partial application (which is easy in JS with the bind method), but true functional currying. It works with any functions of arbitrary, but fixed arity. For variadic functions you would need a different execution trigger, maybe when no arguments are passed any more or an exec method like in #plalx' answer.
How about something like this:
function makeLazy(fn) {
var len = fn.length;
var args = [];
return function lazy() {
args.push.apply(args, arguments);
if (args.length < len) {
return lazy;
} else {
return fn.apply(this, args);
}
}
}
function f(a,b,c) { return a + b + c; }
var lazyF = makeLazy(f);
lazyF(1)(2)(3); // 6
var lazyF = makeLazy(f);
lazyF(1,2)(3); // 6
If you wanted a reusable function (I guess I can't tell exactly what you want), then this would work:
function makeCurry(fn) {
return function curry() {
var args = [].slice.call(arguments);
return function() {
return fn.apply(this, args.concat.apply(args, arguments));
};
}
}
function f(a,b,c) { return a + b + c; }
var curryF = makeCurry(f);
var addOneTwoAnd = curryF(1,2);
addOneTwoAnd(3); // 6
addOneTwoAnd(6); // 9
Please check the curry library.
It can turn any function into curry no matter how many arguments are there.
Example:
> var curry = require('curry');
undefined
> var add = curry(function(a, b, c, d, e) { return a + b + c + d + e; });
undefined
> add(1)
[Function]
> add(1,2,3,4,5)
15
> add(1,2)(3,4)(5)
15
>
The bind() method on function lets you bind the this inside the function as well as bind extra parameters. So, if you pass null for the this parameter, you can use bind() to curry the parameters into the function.
function g(a,b,c){ return a + b + c }
var g_1 = g.bind(null, 1);
console.log(g_1(2, 3)); // Prints 6
var g_1_2 = g.bind(null, 1, 2);
console.log(g_1_2(3)); // Prints 6
Check Javascript Function bind() for details and interactive examples of using bind() to bind parameters.

Categories