Skip to content

Instantly share code, notes, and snippets.

@andrijac
Created December 4, 2019 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrijac/e0ab6456729fa2f65a39d9893d65cb1b to your computer and use it in GitHub Desktop.
Save andrijac/e0ab6456729fa2f65a39d9893d65cb1b to your computer and use it in GitHub Desktop.
From book "How JavaScript Works"
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