Change the parameter like this [function.value(new-value)] - javascript

function add(n) {
return function(x) {
this.value = n;
return this.value + x;
}
}
var add3 = add(3);
var add4 = add(4);
I'm trying to figure out if I can re-write this function above to:
Allow to modify the first parameter like this:
add3.value(1);
console.log(add3(4))
// 5
Also so that the value method returns the current value if no parameter is passed:
add3.value(1);
console.log(add3.value())
// 1

Functions are just objects, so you can assign a property value to it, whose value is a function that modifies n:
function add(n) {
var result = function(x) {
return n + x;
};
result.value = function(x) {
if (typeof x === 'undefined') {
return n;
}
n = x;
};
return result;
}
Why you'd want to do that I don't know, but it's possible.

To use the interface you've described, your inner function will need to return a object with a 'value' method.
eg.
function add (n) {
return {
value: function (x) {
x = x || 0;
return n + x;
}
};
}
But, what it sounds like you're trying to do is currying & partial application. In which case, returning a function is probably simpler.
function add (n) {
return function (x) {
x = x || 0;
return n + x;
};
}
This would be used like so:
var add3 = add(3);
console.log(add3(4)); // output: 7
or, with the default value:
var add4 = add(4);
console.log(add4()); // output: 4

Similar to Felix's answer, but permitting empty inputs, remembering last values and also giving it a valueOf so it can be used like a number itself.
function adder(i) {
i || (i = 0);
var add = function (x) {
return i += (+x || 0); // += modifies i
};
add.value = function (x) {
return !x && x !== 0 ? i : i = (+x || 0); // if x falsy but not zero
};
add.valueOf = function () {
return i;
};
return add;
}
var add = adder();
add.value(1); // 1
add(4); // 5
add(5); // 10
add + 2; // 12, via valueOf
add(); // 10

Related

Function that supports both currying and traditional behaviour for 'n' parameters [duplicate]

This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
Variadic curried sum function
(19 answers)
Closed 10 months ago.
I have the below code wherein, I have wrapped functions to achieve the above behaviour. But unfortunately it returns expected result only when the no of parameters equals to 2.
function baseCurry (func) {
return function (...args) {
if (args.length >= func.length) {
return func.call(this, ...args)
} else {
return baseCurry(func.bind(this, ...args))
}
}
}
function addHelper (x, y) {
return x + y;
}
const superCurry = baseCurry(addHelper);
Test Cases:
console.log(superCurry(1, 5)); // 6
console.log(superCurry(1)(5)); // 6
console.log(superCurry(1)); // [Function (anonymous)]
console.log(superCurry(1)(2)(3)); // Error
console.log(superCurry(1,2)(3)); // Error
I need to change it in such a way that it gives expected result for all n >= 1, where 'n' is the number of parameters
Note:
The params can be passed in any combinations like
console.log(superCurry(1,2)(3)(4))
console.log(superCurry(1,2,3)(5,7)(4)(8,9))
Thanks in advance
I could do something similar to your expectation, but I do need an extra pair of () at the end of the call chain so that the function will know when a function is to be returned and when the value.
function baseCurry (func, value) {
this.value = value ?? 0;
return (...args) => {
if (args.length === 0) {
let val = this.value;
this.value = 0;
return val;
}
for (let index = 0; index < args.length; index += func.length - 1) {
this.value = func(this.value, ...args.slice(index, (index + func.length - 1 <= args.length) ? index + func.length - 1 : undefined));
}
return baseCurry(func, this.value);
}
}
function addHelper (x, y) {
return x + y;
}
const superCurry = baseCurry(addHelper);
console.log(superCurry(1, 5)());
console.log(superCurry(1)(5)());
console.log(superCurry(1)());
console.log(superCurry(1)(2)(3)());
console.log(superCurry(1,2)(3)());
console.log(superCurry(1,2,3)());

closure in javascript with multiple empty calls to sum function

I faced this question in one interview. I did not get how to solve this.
Question: Write a sum function which will add 2 numbers, but numbers can be passed to a function in following ways:
sum(3)(4) // answer should be 7
sum(3)()(4)//answer should be 7
sum(3)()()()()(4) //answer should b 7
I can solve first function using closure, in fact for the second function also I can check the arguments and if arguments length is zero I can again make a call to sum to except next parameter.
But how to make it generic ? Means even your first parameter and last parameter has 'N' number of calls & those can be empty or parameterized, it should return sum.
Recorded a video how to solve it:
https://youtu.be/7hnYMIOVEg0
Text answer:
function sum(numberOne) {
return function innerSum(numberTwo) {
if (typeof(numberTwo) === 'number') {
return numberOne + numberTwo;
}
return innerSum;
}
}
Output:
sum(3)(4); => 7
sum(5)()()(10); => 15
Basically, you need to return inner function (innerSum) up until you receive a value - then you return number.
You could also choose another name - like _sum(), or addToFirstNumber() for your method.
You can always return a function from within a function:
let a;
function sum(value) {
if (typeof value !== "number") {
return sum;
}
if (typeof a !== "number") {
a = value;
return sum;
}
let result = a + value;
a = null;
return result;
}
see https://jsfiddle.net/d9tLh11k/1/
function sum(num1) {
return function sum2(num2) {
if(num2 === undefined) {
return sum2;
}
return num1 + num2;
}
}
console.log(sum(4)()()()(3)); // -> 7
Or in ES6:
const add = num1 => num2 => num2 === undefined ? add(num1) : num1 + num2;
console.log(add(4)()()()()()(3)); // -> 7
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)(3)()()(6));
I have already given answer of this question Here
but according to your question I have modified that
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)(3)()()(6));
Run code like that
console.log(+add(1)(2)(3)()()(6));
This should do it
function sum(num1) {
if (arguments.length === 0){
return sum;
}
return function innerSum(num2) {
if (arguments.length > 0){
return num1 + num2;
}else{
return innerSum;
}
}
}
You can do this in a number of ways, but mostly you'll want named recursion. That is, you can have something like:
sum = start => (...args) => args.length? args[0] + start : sum(start)
but it might look cleaner to write this as:
function sum(start) {
function out(...args) {
return args.length? start + args[0] : out
}
return out;
}

"stringValues" is defined but never used no-unused-vars

I'm new to JS and I am trying to call a function inside another function. When I try it I am getting the lint error.
- stringValues inserts comma in between numbers to display correct formats, for 1000 it displays as 1,000 and for 10000 it displays as 10,000
return Number(unitsOfNumbers.join('')).stringValues();
providing my code and error below.
ERROR:
"stringValues" is defined but never used no-unused-vars
CODE:
import {differentCountriesCurrency} from 'sports-input-utils/lib/formatting';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.appleBrowser = appleBrowser;
exports.appleBrowserWithDecimals = appleBrowserWithDecimals;
function stringValues(x, sep, grp) {
var sx = (''+x).split('.'), s = '', i, j;
sep || (sep = ','); // default seperator
grp || grp === 0 || (grp = 3); // default grouping
i = sx[0].length;
while (i > grp) {
j = i - grp;
s = sep + sx[0].slice(j, i) + s;
i = j;
}
s = sx[0].slice(0, i) + s;
sx[0] = s;
return sx.join('.');
}
function appleBrowser(value, parm) {
var unitsOfNumbers;
if (!value) {
return value;
}
// extract unitsOfNumbers. if no unitsOfNumbers, fill in a zero.
unitsOfNumbers = value.match(/\d/g) || ['0'];
return Number(unitsOfNumbers.join('')).stringValues();
}
function appleBrowserWithDecimals(value, parm) {
var unitsOfNumbers;
if (!value) {
return value;
}
// extract unitsOfNumbers. if no unitsOfNumbers, fill in a zero.
unitsOfNumbers = value.match(/\d/g) || ['0'];
// zero-pad a one-digit input
if (unitsOfNumbers.length === 1) {
unitsOfNumbers.unshift('0');
}
// add a decimal point
unitsOfNumbers.splice(unitsOfNumbers.length - 2, 0, '.');
return Number(unitsOfNumbers.join('')).stringValues();
}
//# sourceMappingURL=formatting.js.map
exports.limitMaximumLength = limitMaximumLength;
function limitMaximumLength(value, parm) {
if (value.length < parm) {
return value;
} else {
return value.substring(0, parm);
}
}
exports.differentCountriesCurrencyWithMaxLen = differentCountriesCurrencyWithMaxLen;
function differentCountriesCurrencyWithMaxLen (value) {
var isSafari;
return differentCountriesCurrency(limitMaximumLength(value, 7));
isSafari = navigator.userAgent.indexOf("Safari") > -1;
if (isSafari) {
return appleBrowser(limitMaximumLength(value, 7));
}
}
Not worrying about other linting errors or checking anything about the logic (haven't checked if it does what you want or not), I can remove the no-unused-vars error like this:
import {differentCountriesCurrency} from 'sports-input-utils/lib/formatting';
Object.defineProperty(exports, '__esModule', {
value: true
});
function stringValues(x, sep, grp) {
var sx = (''+x).split('.'), s = '', i, j;
sep || (sep = ','); // default seperator
grp || grp === 0 || (grp = 3); // default grouping
i = sx[0].length;
while (i > grp) {
j = i - grp;
s = sep + sx[0].slice(j, i) + s;
i = j;
}
s = sx[0].slice(0, i) + s;
sx[0] = s;
return sx.join('.');
};
exports.appleBrowser = function (value, parm) {
var unitsOfNumbers;
if (!value) {
return value;
}
// extract unitsOfNumbers. if no unitsOfNumbers, fill in a zero.
unitsOfNumbers = value.match(/\d/g) || ['0'];
return stringValues(Number(unitsOfNumbers.join('')));
};
exports.appleBrowserWithDecimals = function (value, parm) {
var unitsOfNumbers;
if (!value) {
return value;
}
// extract unitsOfNumbers. if no unitsOfNumbers, fill in a zero.
unitsOfNumbers = value.match(/\d/g) || ['0'];
// zero-pad a one-digit input
if (unitsOfNumbers.length === 1) {
unitsOfNumbers.unshift('0');
}
// add a decimal point
unitsOfNumbers.splice(unitsOfNumbers.length - 2, 0, '.');
return stringValues(Number(unitsOfNumbers.join('')));
};
exports.limitMaximumLength = function (value, parm) {
if (value.length < parm) {
return value;
} else {
return value.substring(0, parm);
}
};
exports.differentCountriesCurrencyWithMaxLen = function (value) {
var isSafari;
return differentCountriesCurrency(limitMaximumLength(value, 7));
// ^^^ There's no way this ^^^ is what you want.
// The rest of the function is always ignored. You've already returned.
isSafari = navigator.userAgent.indexOf("Safari") > -1;
if (isSafari) {
return appleBrowser(limitMaximumLength(value, 7));
}
};
To remove the error, I did exactly what #JosephYoung says. You haven't added stringValues to whatever Number returns. You declared it globally.
So don't do this:
return Number(unitsOfNumbers.join('')).stringValues();
That pretends there's another stringValues as a function-property on Number's return value. Your function stringValues exists at global scope, and is never called.
To call what you declared, you do this:
return stringValues(Number(unitsOfNumbers.join('')));
One important readability issue to notice: Instead of the lines you have like this...
exports.limitMaximumLength = limitMaximumLength;
function limitMaximumLength(value, parm) {
... go ahead and put the assignment on a single line like this...
exports.limitMaximumLength = function (value, parm) {
Makes it easier to tell what you're exporting and what's a "private" utility function.

How to change a variable to something if it's undefined?

I don't have my script completed yet or anything so I can't post the code. Basically I need a variable to change and keep going through a function increasing by one until it reaches its destination. Something like:
function one(a) {
var x = a;
var max = 3;
if (a < 3) {
// some code
two(x);
} else {
// function will end here quitting the whole thing and possibly other code
}
}
function two(x) {
var change = x+1;
one(change);
}
It all works how I need it but when I first enter function one how would I make it so when x = a doesn't have a value that it will by default be 0?
something like...
function one(a) {
var x = a;
var max = 3;
if (x = undefined) {
x = 0;
} else {
if (x < 3) {
// some code
two(x);
} else {
// function will end here quitting the whole thing and possibly other code
}
}
}
function two(x) {
var change = x+1;
one(change);
}
Any ideas?
You could do this:
function one(a) {
var x = a || 0;
if (x < 3) {
//debugger;
two(x);
} else {
// function will end here quitting the whole thing and possibly other code
alert('Done');
}
}
function two(x) {
x++;
one(x);
}
one();
FIDDLE
var x = a || 0 means x is a if a can be asserted as true or 0.
x++ means x = x + 1
You can check to see if the variable is defined and send it in the functions argument by using the short hand conditional.
typeof(a)=="undefined" ? 0 : a;
You can change your code to:
function one(a) {
var x = (typeof(a)=="undefined" ? 0 : a);
var max = 3;
if (x < 3) {
// some code
two(x);
} else {
// function will end here quitting the whole thing and possibly other code
return;
}
}
Fiddle: http://jsfiddle.net/gBBL2/
var x = (typeof a === 'undefined') ? 0 : a;
If a is undefined, use 0. Otherwise use a as the value of x.

Variadic curried sum function

I need a js sum function to work like this:
sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10
etc.
I heard it can't be done. But heard that if adding + in front of sum can be done.
Like +sum(1)(2)(3)(4). Any ideas of how to do this?
Not sure if I understood what you want, but
function sum(n) {
var v = function(x) {
return sum(n + x);
};
v.valueOf = v.toString = function() {
return n;
};
return v;
}
console.log(+sum(1)(2)(3)(4));
JsFiddle
This is an example of using empty brackets in the last call as a close key (from my last interview):
sum(1)(4)(66)(35)(0)()
function sum(firstNumber) {
let accumulator = firstNumber;
return function adder(nextNumber) {
if (nextNumber === undefined) {
return accumulator;
}
accumulator += nextNumber;
return adder;
}
}
console.log(sum(1)(4)(66)(35)(0)());
I'm posting this revision as its own post since I apparently don't have enough reputation yet to just leave it as a comment. This is a revision of #Rafael 's excellent solution.
function sum (n) {
var v = x => sum (n + x);
v.valueOf = () => n;
return v;
}
console.log( +sum(1)(2)(3)(4) ); //10
I didn't see a reason to keep the v.toString bit, as it didn't seem necessary. If I erred in doing so, please let me know in the comments why v.toString is required (it passed my tests fine without it). Converted the rest of the anonymous functions to arrow functions for ease of reading.
New ES6 way and is concise.
You have to pass empty () at the end when you want to terminate the call and get the final value.
const sum= x => y => (y !== undefined) ? sum(x + y) : x;
call it like this -
sum(10)(30)(45)();
Here is a solution that uses ES6 and toString, similar to #Vemba
function add(a) {
let curry = (b) => {
a += b
return curry
}
curry.toString = () => a
return curry
}
console.log(add(1))
console.log(add(1)(2))
console.log(add(1)(2)(3))
console.log(add(1)(2)(3)(4))
Another slightly shorter approach:
const sum = a => b => b? sum(a + b) : a;
console.log(
sum(1)(2)(),
sum(3)(4)(5)()
);
Here's a solution with a generic variadic curry function in ES6 Javascript, with the caveat that a final () is needed to invoke the arguments:
const curry = (f) =>
(...args) => args.length? curry(f.bind(0, ...args)): f();
const sum = (...values) => values.reduce((total, current) => total + current, 0)
curry(sum)(2)(2)(1)() == 5 // true
Here's another one that doesn't need (), using valueOf as in #rafael's answer. I feel like using valueOf in this way (or perhaps at all) is very confusing to people reading your code, but each to their own.
The toString in that answer is unnecessary. Internally, when javascript performs a type coersion it always calls valueOf() before calling toString().
// invokes a function if it is used as a value
const autoInvoke = (f) => Object.assign(f, { valueOf: f } );
const curry = autoInvoke((f) =>
(...args) => args.length? autoInvoke(curry(f.bind(0, ...args))): f());
const sum = (...values) => values.reduce((total, current) => total + current, 0)
curry(sum)(2)(2)(1) + 0 == 5 // true
Try this
function sum (...args) {
return Object.assign(
sum.bind(null, ...args),
{ valueOf: () => args.reduce((a, c) => a + c, 0) }
)
}
console.log(+sum(1)(2)(3,2,1)(16))
Here you can see a medium post about carried functions with unlimited arguments
https://medium.com/#seenarowhani95/infinite-currying-in-javascript-38400827e581
Try this, this is more flexible to handle any type of input. You can pass any number of params and any number of paranthesis.
function add(...args) {
function b(...arg) {
if (arg.length > 0) {
return add(...[...arg, ...args]);
}
return [...args, ...arg].reduce((prev,next)=>prev + next);
}
b.toString = function() {
return [...args].reduce((prev,next)=>prev + next);
}
return b;
}
// Examples
console.log(add(1)(2)(3, 3)());
console.log(+add(1)(2)(3)); // 6
console.log(+add(1)(2, 3)(4)(5, 6, 7)); // 28
console.log(+add(2, 3, 4, 5)(1)()); // 15
Here's a more generic solution that would work for non-unary params as well:
const sum = function (...args) {
let total = args.reduce((acc, arg) => acc+arg, 0)
function add (...args2) {
if (args2.length) {
total = args2.reduce((acc, arg) => acc+arg, total)
return add
}
return total
}
return add
}
document.write( sum(1)(2)() , '<br/>') // with unary params
document.write( sum(1,2)() , '<br/>') // with binary params
document.write( sum(1)(2)(3)() , '<br/>') // with unary params
document.write( sum(1)(2,3)() , '<br/>') // with binary params
document.write( sum(1)(2)(3)(4)() , '<br/>') // with unary params
document.write( sum(1)(2,3,4)() , '<br/>') // with ternary params
ES6 way to solve the infinite currying. Here the function sum will return the sum of all the numbers passed in the params:
const sum = a => b => b ? sum(a + b) : a
sum(1)(2)(3)(4)(5)() // 15
function add(a) {
let curry = (b) => {
a += b
return curry;
}
curry[Symbol.toPrimitive] = (hint) => {
return a;
}
return curry
}
console.log(+add(1)(2)(3)(4)(5)); // 15
console.log(+add(6)(6)(6)); // 18
console.log(+add(7)(0)); // 7
console.log(+add(0)); // 0
Here is another functional way using an iterative process
const sum = (num, acc = 0) => {
if !(typeof num === 'number') return acc;
return x => sum(x, acc + num)
}
sum(1)(2)(3)()
and one-line
const sum = (num, acc = 0) => !(typeof num === 'number') ? acc : x => sum(x, acc + num)
sum(1)(2)(3)()
You can make use of the below function
function add(num){
add.sum || (add.sum = 0) // make sure add.sum exists if not assign it to 0
add.sum += num; // increment it
return add.toString = add.valueOf = function(){
var rtn = add.sum; // we save the value
return add.sum = 0, rtn // return it before we reset add.sum to 0
}, add; // return the function
}
Since functions are objects, we can add properties to it, which we are resetting when it's been accessed.
we can also use this easy way.
function sum(a) {
return function(b){
if(b) return sum(a+b);
return a;
}
}
console.log(sum(1)(2)(3)(4)(5)());
To make sum(1) callable as sum(1)(2), it must return a function.
The function can be either called or converted to a number with valueOf.
function sum(a) {
var sum = a;
function f(b) {
sum += b;
return f;
}
f.toString = function() { return sum }
return f
}
function sum(a){
let res = 0;
function getarrSum(arr){
return arr.reduce( (e, sum=0) => { sum += e ; return sum ;} )
}
function calculateSumPerArgument(arguments){
let res = 0;
if(arguments.length >0){
for ( let i = 0 ; i < arguments.length ; i++){
if(Array.isArray(arguments[i])){
res += getarrSum( arguments[i]);
}
else{
res += arguments[i];
}
}
}
return res;
}
res += calculateSumPerArgument(arguments);
return function f(b){
if(b == undefined){
return res;
}
else{
res += calculateSumPerArgument(arguments);
return f;
}
}
}
let add = (a) => {
let sum = a;
funct = function(b) {
sum += b;
return funct;
};
Object.defineProperty(funct, 'valueOf', {
value: function() {
return sum;
}
});
return funct;
};
console.log(+add(1)(2)(3))
After looking over some of the other solutions on here, I would like to provide my two solutions to this problem.
Currying two items using ES6:
const sum = x => y => (y !== undefined ) ? +x + +y : +x
sum(2)(2) // 4
Here we are specifying two parameters, if the second one doesnt exist we just return the first parameter.
For three or more items, it gets a bit trickier; here is my solution. For any additional parameters you can add them in as a third
const sum = x => (y=0) => (...z) => +x + +y + +z.reduce((prev,curr)=>prev+curr,0)
sum(2)()()//2
sum(2)(2)()//4
sum(2)(2)(2)//6
sum(2)(2)(2,2)//8
I hope this helped someone

Categories

Resources