Function that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times that must multiply the digits in num until it reach a single digit.
var persistenceCount = 0;
function persistence(num) {
var arr = _parseToNumericArray(num);
if (_checkLength(arr)) {
return persistenceCount;
} else {
persistenceCount++;
var newNum = _getMultiple(arr);
persistence(newNum);
}
}
function _parseToNumericArray(num) {
var n = num.toString().split("");
return n.map(function(elem) {
return parseInt(elem);
});
}
function _checkLength(arr) {
return arr.length === 1;
}
function _getMultiple(arr) {
return arr.reduce(function(a, b) {
return a * b;
});
}
console.log(persistence(39)); // Getting output as undefined
Like #Keith said, you forgot to return the value.
var persistenceCount = 0;
function persistence(num) {
var arr = _parseToNumericArray(num);
if (_checkLength(arr)) {
return persistenceCount;
} else {
persistenceCount++;
var newNum = _getMultiple(arr);
return persistence(newNum);
}
}
function _parseToNumericArray(num) {
var n = num.toString().split("");
return n.map(function(elem) {
return parseInt(elem);
});
}
function _checkLength(arr) {
return arr.length === 1;
}
function _getMultiple(arr) {
return arr.reduce(function(a, b) {
return a * b;
});
}
console.log(persistence(39)); // Outputs 3
There is no return statement in the else. So return undefined.
By default, in JavaScript, a function always return undefined if nothing is returned.
Related
i'm trying to find a solution to this exercise:
Implement the calculate function that adds an object that gives the ability to do the four
mathematical operations (addition, subtraction, multiplication and division) on the same number and finally print out the result.
function calculate() {
}
const calculator = calculate();
calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(calculator)
so, what is the right way to solve this (and if you can add comment will be appreciated
no need to put so many this and function...
in this way you have a closure value.
=> calc_00.val = 20;
will not change the result (it just add a new property if jso is not freeze )
or throw an error in strict mode
"use strict";
function calculate( initVal = 0 ) // default value is zero
{
let
val = initVal // closure value
, jso =
{ add(v) { val += v; return this }
, sub(v) { val -= v; return this }
, multiply(v) { val *= v; return this }
, divide(v) { val /= v; return this }
, printResult() { return val }
}
Object.freeze(jso)
return jso
}
const
calc_00 = calculate()
, calc_10 = calculate(10)
;
// calc_00.yop = ()=>null; // Uncaught TypeError: can't define property "yop": Object is not extensible
// calc_00.sub = ()=>null; // Uncaught TypeError: "sub" is read-only
// calc_00.val = 20; // Uncaught TypeError: can't define property "val": Object is not extensible
calc_00.add(2).add(4).multiply(3).sub(1).sub(3).divide(2);
calc_10.add(10).multiply(3);
console.log( calc_00.printResult(), calc_10.printResult() ) // 7 , 60
You can return the object itselft.
function calculate() {
return {
result: 0,
add: function(num) {
this.result += num;
return this;
},
sub: function(num) {
this.result -= num;
return this;
},
multiply: function (num) {
this.result *= num;
return this;
},
divide: function (num) {
this.result /= num;
return this;
},
printResult: function () {
return this.result;
}
}
};
const calculator = calculate();
const result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(result);
Make sure to understand how this works in JavaScript. For instance, using functions is different than using arrow functions.
Reference: JavaScript this
Alternative solution using closure
function calculate() {
let result = 0;
return {
add: function(num) {
result += num;
return this;
},
sub: function(num) {
result -= num;
return this;
},
multiply: function (num) {
result *= num;
return this;
},
divide: function (num) {
result /= num;
return this;
},
printResult: function () {
return result;
}
}
};
const calculator = calculate();
const result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(result);
I'm trying to implement memoization in javascript.
here's the code:
function memoize(func) {
var history = {}
var inner = function(n) {
if (n in history) {
return history[n];
}
let result = func(n)
history[n] = result;
return result;
}
return inner;
}
function fib(n) {
if (n <= 1) {
return n;
}
return fib(n-1) + fib(n-2)
}
/*
fib = memoize(fib);
console.log(fib(20)) // O(n)
*/
/*
fib2 = memoize(fib);
console.log(fib2(20)) // O(2^n)
*/
it works.. I can calculated values in O(n) but I lost the original function. any way to still have the original fib function accessible?
thanks
If you want to retain the original un-memoized version of fib you'll need to modify fib in some way, such as passing your recursive function as an argument. Otherwise, the recursive fib calls will remain as the un-memoized versions of your function.
eg:
function memoize(func) { // potentially update this to accept as hash function to calculate the key for `history` to make this more generic
var history = {}
var inner = function(n, ...args) {
if (n in history) {
return history[n];
}
let result = func(n, ...args);
history[n] = result;
return result;
}
return inner;
}
function fib(n, recursiveFn = fib) {
if (n <= 1) {
return n;
}
return recursiveFn(n - 1, recursiveFn) + recursiveFn(n - 2, recursiveFn)
}
const fastFib = memoize(fib);
console.log(fastFib(40, fastFib)); // O(n)
const slowFib = fib(40); // O(2^n)
console.log(slowFib);
My goal with the code below is to have whatever function passed into fn to ONLY be invoked once. e.g. result returns 5 and the repeated invocation below should also return that same number. What I have right now keeps returning a new number instead of the same one.
function once(fn) {
var done = false;
return function () {
if (!done) {
done = true;
return fn.apply(this, arguments);
} else if (done) {
return fn.apply(this, arguments);
}
};
}
function add(x, y) {
return x + y;
}
var addOnce = once(add);
var result = addOnce(2, 3);
result = addOnce(4, 4);
For getting the same value, you could store the value and return it for every call.
function once(fn) {
var done = false,
value;
return function() {
if (!done) {
done = true;
value = fn.apply(this, arguments);
}
return value;
};
}
function add(x, y) {
return x + y;
}
var addOnce = once(add);
console.log(addOnce(2, 3)); // 5
console.log(addOnce(4, 4)); // 5
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)
I am beginner in Javascript
I am always getting true returned whatever the values of my variables,
It should return true if a and b are both even, but false otherwise.
Thanks for your help.
https://repl.it/9nH/1675
var a = 4;
var b= 5;
function areBothEqual (a, b) {
if(a===b) {
return true;
}else {
return false
}
}
var result = areBothEqual();
document.write(result)
you are not passing the arguments to your function:
areBothEqual(a,b)
you had:
areBothEqual()
cheers
The issue is that you are requesting the arguments a and b in the line function areBothEqual (a, b), but they are never actually passed. Just replace the (a, b) with empty brackets (), as you can use the previously defined a and b instead.
var a = 4;
var b= 5;
function areBothEqual() {
if(a===b) {
return true;
} else {
return false
}
}
areBothEqual()
var a = 4;
var b= 5;
function areBothEqual (a, b) {
console.log(a);
console.log(b);
if(a===b) {
return true;
}else {
return false
}
}
areBothEqual();
They are 'undefined' both are equals...