Recursive Call and Function Definition [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am attempting to implement what should be a simple coding interview-like question. However, I'm having difficulty making the recursive call:
(function () {
if(typeof Algorithms === "undefined") {
window.Algorithms = {};
}
// Write a method, digital_root(num).
// It should sum the digits of a positive integer.
// If it is greater than or equal to 10, sum the digits of the resulting number.
// Keep repeating until there is only one digit in the result, called the "digital root".
// Do not use string conversion within your method.
Algorithms.digitalRoot = function (number) {
if (number < 10) {
return number;
}
var sum = 0;
while(number != 0) {
sum += number % 10;
number = Math.floor(number/10);
}
this.digitalRoot(sum);
};
The spec looks like so:
it("65,536 should return 7", function() {
expect(Algorithms.digitalRoot(65536)).toBe(7);
});
it("1,853 should return 8", function() {
expect(Algorithms.digitalRoot(1853)).toBe(8);
});
I thought what happened was: Algorithms is an object that has digitalRoot as a property (specifically a function). Thus, when Algorithms.digitalRoot(number_here) is called, the this should refer to Algorithms. Therefore, I wrote the recursive call like this.digitalRoot(sum). Could someone please correct my incorrect thinking?
The error reads as below:
digitalRoot 65,536 should return 7. Expected undefined to be 7. Error:
Expected undefined to be 7.
at new jasmine.ExpectationResult (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:114:32)
at null.toBe (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:1235:29)
at null. (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/spec/algorithms_spec.js:3:43)
at jasmine.Block.execute (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:1064:17)
at jasmine.Queue.next_ (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2096:31)
at jasmine.Queue.start (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2049:8)
at jasmine.Spec.execute (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2376:14)
at jasmine.Queue.next_ (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2096:31)
at jasmine.Queue.start (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2049:8)
at jasmine.Suite.execute (file:///C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2521:14)

You don't return anything from your function unless number < 10. That is why you are getting undefined instead of 7. Your expectation about this was correct.
Return the value this.digitalRoot(sum);:
...
number = Math.floor(number/10);
}
return this.digitalRoot(sum);
};

Related

How to check the array is of how many dimension in javascript? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For example I have an array as follows & expected output is given.
In javascript how can we determine dynamically how many levels are there in my array ary.
var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]];
Output: 3
var ary = ["a","b",["c","d"],"e",["f","g","i"]];
Output: 2
var ary = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
Output: 4
Here is a reccursive function that will traverse through the depths of the array and track the maximum of it. Note that the tracking is done via properties attach to the function itself.
var ary1 = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
function getDimension(arr, start) {
//Attach depth tracking properties to the function
if (start){
getDimension.depth = 0;
getDimension.maxDepth = 0;
}
//Track max depth
getDimension.depth++
if (getDimension.depth > getDimension.maxDepth)
getDimension.maxDepth++;
//Manage recursion
for (let element of arr)
if (element instanceof Array)
getDimension(element);
getDimension.depth--;
//In first level at this point
if (getDimension.depth === 0)
return getDimension.maxDepth;
}
let d = getDimension(ary1, true);
console.log(d);

Javascript returning a value from a function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Here is a simplified version of my function and calling it.
When i console log the gameOver it should be "Treasure" or Huntress or false
// calling the function
var gameOver = this._checkGameOver;
_checkGameOver(){
var round = 1;
var gold = this._deck.filter(x => x =='Treasure').length;
var trap = this._deck.filter(x => x =='Trap').length;
if(gold == 0){
return('Adventurer');
}
else if(trap == 0 || round == 5){
return('Huntress');
}
else{
return false;
}
}
I think you don't call the function.
Try gameOver() instead of gameOver
You're assigning the actual method to gameOver, not its return value. Make your function call as follows:
let gameOver = this._checkGameOver();

Why is this for loop not logging sum? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to use this for loop within the function to get the sum of an array. However, when I call the function I receive NaN.
tips = [1,2,3,4,5]
function sumTip (tips){
for (i=0; i<tips.length; i++){
var total = total + tips[i];
console.log(total);
}
}
sumTip();
Error 1 - Wrong syntax. It should be tips.length and not length.tips.
Error 2 - You haven't given the parameter to the function when you
are calling it. It should be sumTip(tips);
Error 3 - i is not declared in the loop.
Error 4 - For your logic to work, the total should be declared and initialised to zero outside the for loop and then used inside the loop.
You are doing - var total = total + tips[i]; when total hasn't been defined yet so the in the expression total + tips[i] evaluates to NaN and that's why you are getting Nan as output.
The following code should work after correcting the above mentioned errors -
tips = [1,2,3,4,5]
function sumTip (tips){
var total = 0;
for (var i=0; i<tips.length; i++){
total = total + tips[i];
console.log(total);
}
}
sumTip(tips);
Couple problems you're running into here. First, in your last line, when you call sumTip, you never pass it the array, like: sumTip(tips). Second, you are resetting total everytime you loop, it should be set up like:
var total = 0;
for (var i=0; i<tips.length; i++){
total += tips[i];
console.log(total);
}
This all could just be reduced though: let sum = tips.reduce((a, b) => a + b, 0)

Array.lenght returns undefined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I wish to get the length of an array so I can use it further in another function but it returns undefined. This piece of code gets a file, opens it and splits it for each new line. I'm trying to get the length of the array but returns undefined.
function readBatFile(bfile){
var rawFile1 = new XMLHttpRequest();
rawFile1.open("GET", bfile, false);
rawFile1.onreadystatechange = function ()
{
if(rawFile1.readyState === 4)
{
if(rawFile1.status === 200 || rawFile.status === 0)
{
var allCode = rawFile1.responseText;
var ary = new Array;
ary = allCode.split(/.*\n/gm);
var rcount = ary.lenght;
document.getElementById('test').innerHTML = rcount;
}
}
};
rawFile1.send(null);
}
It is spelled length not lenght.
It should be:
var rcount = ary.length;

Convert string into array of int [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I want to convert "1,2,3" to [1,2,3].
But there is an exception when converting "" to array. Because I get [""]. That is not valid for my case. So I need to check is it number or String. Let see this in code
function someWayToParse(some_string) {
var final_product = [];
var tmp_array = some_string.split(',');
//if some_string == "" tmp_array will result [""];
if (tmp_array[0].length===0)
return [];
for (var item in tmp_array)
final_product.push(parseInt(tmp_array[item], 10));
return final_product;
}
var stringToParse = "1,2,3";
var array_of_ints = someWayToParse(stringToParse);
I am just looking the best way to do this in a function and avoid possible mistakes.
Please be memory efficient, for my curiosity's sake.
Smaller code for it would be:
function myConverter(string) {
if (!string) return [];
return string.split(',').map(Number);
}
console.log(myConverter('1,2,3'));

Categories