I'm trying to understand how to use functions in JS.
This code converting decimal numbers to binary numbers:
for (j = 13; j <= 16; j ) {
res = ""
number = j
while (number > 0) {
res = res number % 2
number = Math.floor(number / 2)
}
len = res.length
rev=""
for (i = 1; i <= len; i ) {
rev = rev res[res.length - i]
}
console.log(rev)
}
but when I'm trying to put this code into a function, the function returns only the first or the last value. What am I doing wrong?
function f(min, max) {
for (j = min; j <= max; j ) {
res = ""
number = j
while (number > 0) {
res = res number % 2
number = Math.floor(number / 2)
}
len = res.length
rev=""
for (i = 1; i <= len; i ) {
rev = rev res[res.length-i]
}
}
return rev
}
console.log(f(13,15))
CodePudding user response:
You have to store the result of each iteration in array.
function f(min, max) {
const results = []
for (j = min; j <= max; j ) {
res = ""
number = j
while (number > 0) {
res = res number % 2
number = Math.floor(number / 2)
}
len = res.length
rev=""
for (i = 1; i <= len; i ) {
rev = rev res[res.length-i]
}
results.push(rev)
}
return results
}
console.log(f(13,15))
Also you should declare your variables in JavaScript, because not doing that can lead to bugs https://www.geeksforgeeks.org/what-happen-when-we-directly-assign-the-variable-without-declaring-it-in-javascript/
CodePudding user response:
You need a variable for gathering all intermediate results.
You could take declarations for all variables.
function f(min, max) {
const result = [];
for (let j = min; j <= max; j ) {
let number = j,
temp = "";
while (number > 0) {
temp = number % 2;
number = Math.floor(number / 2);
}
result.push(temp);
}
return result;
}
console.log(f(13, 15));
CodePudding user response:
You should divide your code into to functions
one that turn a number in binary string (I also included the existing js version)
and one that create a list of element between min and max and iterate onto them
const toBin = n => n.toString(2)
const customToBin = n => {
const res = []
let number = n
while (number > 0) {
res.push(number % 2)
number = Math.floor(number / 2)
}
return res.reverse().join('')
}
const createInterval = (min, max) => Array(max - min 1).fill(min).map((_, i) => min i)
const f = (min, max) => createInterval(min, max).map(customToBin)
console.log(f(13, 16))