'Array.join('') is not working as it should inside of my recursive function
I am attempting to use a recursive approach in order to write a function that will take in a binary string, break it apart into 8 bit sections, and return the string translated to ASCII. As far as I can tell from the running debugger, my function should be working. The only problem I'm running into is that when I call join('') on my 'currentArray' variable, it is not in fact joining the array. Any input would be helpful into what I am doing wrong here.
function binaryToString(binaryBlob, finalString = []) {
if (binaryBlob.length === 0) return finalString.join('');
let currentArray = [];
let binaryArray = binaryBlob.split('');
currentBit = binaryArray.splice(0, 8);
currentArray.push(currentBit);
let joinedString = currentArray.join('');
let base10String = Number(joinedString);
let ASCII = String.fromCharCode(base10String);
finalString.push(ASCII);
return binaryToString(binaryArray.join(''), currentArray, finalString);
};
Expected outputs:
console.log(binaryToString('010000010100001001000011')); // should return 'ABC'
console.log(binaryToString('001101100011011100111000')); // should return '678'
Solution 1:[1]
A couple things:
- Having variables properly named after their type helps for clarity. Name an array
finalArrinstead offinalString, etc. currentArraydoesn't seem to be necessary. Use slice directly on the string to get the first 8 characters for the byte, and slice again to provide the remaining characters to the next call.
Here is a slightly refactored version that makes it clearer:
function binaryToString(binaryStr, asciiArr = []) {
if (binaryStr.length === 0) {
return asciiArr.join('');
}
const byteStr = binaryStr.slice(0, 8);
const remaining = binaryStr.slice(8);
const byte = parseInt(byteStr, 2); // `2` indicates base of input string
const ascii = String.fromCharCode(byte);
asciiArr.push(ascii);
return binaryToString(remaining, asciiArr);
};
console.log(binaryToString('010000010100001001000011')); // 'ABC'
console.log(binaryToString('001101100011011100111000')); // '678'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
