Created
December 4, 2019 10:39
-
-
Save andrijac/e0ab6456729fa2f65a39d9893d65cb1b to your computer and use it in GitHub Desktop.
From book "How JavaScript Works"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deconstruct(number){ | |
let sign = 1; | |
let coefficient = number; | |
let exponent = 0; | |
// Remove sign from the coefficient | |
if(coefficient < 0){ | |
coefficient = -coefficient; | |
sign = -1; | |
} | |
if(Number.isFinite(number) && number !== 0){ | |
//================================================= | |
// Reduce coefficient | |
exponent = -1128; // Exponent of Number.MIN_VALUE | |
let reduction = coefficient; | |
// Divide by 2 until we have shifted all | |
// bits away to zero. | |
while(reduction !== 0){ | |
exponent += 1; | |
reduction /= 2; | |
} | |
//================================================= | |
// Reduce exponent | |
// Bring exponent to zero so number can be viewed as integer | |
reduction = exponent; | |
while(reduction > 0){ | |
coefficient /= 2; | |
reduction -= 1; | |
} | |
while(reduction < 0){ | |
coefficient *= 2; | |
reduction += 1; | |
} | |
} | |
return { | |
equation: `${sign} * ${coefficient} * (2 ^ ${exponent})`, | |
sign, | |
coefficient, | |
exponent, | |
number, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment