javascriptfunctionbinarydecimalsquare

How can I take square of a number that come from a function?


I am new to javascript and coding.I can't take a square of a number which comes from a function.I wrote below what I want to do.Thank you all.

// BİNARY to DECİMAL 

// (100110)2 > (1 × 2⁵) + (0 × 2⁴) + (0 × 2³) + (1 × 2²) + (1 × 2¹) + (0 × 2⁰) = 38

let binary= prompt("Write a Binary Number");

function binaryToDecimalConverter(binary){
    let decimal=0;
    let power=0;
    for(let i=binary.length-1; i>=0; i--){
        decimal+=Number(binary.charAt(i)) * Math.pow(2,power);
        power++;
    }
    console.log("Decimal : " + decimal);
    console.log(squareIt(decimal));
    
}


binaryToDecimalConverter(binary);

function squareIt(decimal){  //38 is here and I want to get it like: (3^2 + 8^2)=73 as result ??
    let sNumber=decimal.toString();
    let total=0;
    for(let i=sNumber.length-1; i>=0; i--){
        total+=Number(sNumber.charAt(i))*Math.pow(sNumber,2);
        
    }
    return total;    
}




I wanted to convert binary number to decimal which entered by user,also I wanted to take square of each character of that number and sum up them.


Solution

  • You can split a number into chars and use Array::reduce():

    let binary= prompt("Write a Binary Number");
    
    function binaryToDecimalConverter(binary){
        let decimal=0;
        let power=0;
        for(let i=binary.length-1; i>=0; i--){
            decimal+=Number(binary.charAt(i)) * Math.pow(2,power);
            power++;
        }
        console.log("Decimal : " + decimal);
        console.log(squareIt(decimal));
        
    }
    
    
    binaryToDecimalConverter(binary);
    
    function squareIt(decimal){  //38 is here and I want to get it like: (3^2 + 8^2)=73 as result ??
        return decimal.toString().split('').reduce((sum, c) => sum + c * c, 0);
    }