A program of calc sum ā with new and smart code in JavaScript š„.
Roshan kumar
Posted on September 20, 2020
Create function in JavaScript that's takes single arguments and return sum of all previous arguments without using global variable.
Here we always try to find short and smart š code for doing same task.
First we try to do this task with simple approach then move forward.
When we create diagram in mind first we think to take an global variable that store data for you, But that's always a bad idea for smart š developer.
function calc() {
// creating private valriable
let value = 0;
// private function
function changeBy(val) {
value += val;
}
// returning an object
return {
// add method
add: function (i) {
changeBy(i);
},
// return value
value: function () {
return value;
}
}
}
// making mycalc function with calc
let mycalc = calc()
// adding number.
mycalc.add(12)
mycalc.add(15)
// print to console
console.log(mycalc.value())
// output is 27
Here we seem like we have long code, and also we don't have es-6 smart features, so let's begin š.
let calc = () => {
// creating private valriable
let value = 0;
// private function
let changeBy = val => value += val;
// returning an object
return {
// add method
add: (i) => changeBy(i),
// return value
value: () => value
}
}
// making mycalc function with calc
let mycalc = calc()
// adding number.
mycalc.add(12)
mycalc.add(15)
// print to console
console.log(mycalc.value())
// still output is 27 but with smart code.
Now if see code, that's pretty short.
let calc = () => {
let value = 0;
let changeVal = val => (value += val);
return {
add: (i) => changeVal(i)
}
}
But a thing is noticeable why we use private function š let's remove it.
let calc = () => {
let value = 0;
return {
add: i => value += i
}
}
We removed many lined of code to making simpler, but still we have an issue with that code. We need a function that's take arguments every time and return sum of all previous and current arguments. But when use our function we feel like we using any class methods and it's properties, let's solve this issue.
- To solving this issue we need to wrap calc function in () parenthesis, and change the name of function calc to sum and call that's function in sum function š.
- And replace object with function in return statement.
let sum = (
i => {
let v = i;
return i => v += i
}
)(0);
Here we change many things like we don't return a object return value only, Zero is starting value of sum function.
Now our task is Completed
let sum = (i => { let v = i; return i => v += i })(0);
console.log(sum(14)) /* output --> 14 */
console.log(sum(13)) /* output --> 27 */
console.log(sum(10)) /* output --> 37 */
final result
let sum = (a => b => a += b )(0)
šššš
š šŖ š
š©
Roshan kumar
Posted on September 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.