simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

index.js (1175B)


      1 export default function parse(input) {
      2   input = input.toUpperCase();
      3   var splitIndex = input.indexOf("P");
      4   var mantissa, exponent;
      5 
      6   if (splitIndex !== -1) {
      7     mantissa = input.substring(0, splitIndex);
      8     exponent = parseInt(input.substring(splitIndex + 1));
      9   } else {
     10     mantissa = input;
     11     exponent = 0;
     12   }
     13 
     14   var dotIndex = mantissa.indexOf(".");
     15 
     16   if (dotIndex !== -1) {
     17     var integerPart = parseInt(mantissa.substring(0, dotIndex), 16);
     18     var sign = Math.sign(integerPart);
     19     integerPart = sign * integerPart;
     20     var fractionLength = mantissa.length - dotIndex - 1;
     21     var fractionalPart = parseInt(mantissa.substring(dotIndex + 1), 16);
     22     var fraction = fractionLength > 0 ? fractionalPart / Math.pow(16, fractionLength) : 0;
     23 
     24     if (sign === 0) {
     25       if (fraction === 0) {
     26         mantissa = sign;
     27       } else {
     28         if (Object.is(sign, -0)) {
     29           mantissa = -fraction;
     30         } else {
     31           mantissa = fraction;
     32         }
     33       }
     34     } else {
     35       mantissa = sign * (integerPart + fraction);
     36     }
     37   } else {
     38     mantissa = parseInt(mantissa, 16);
     39   }
     40 
     41   return mantissa * (splitIndex !== -1 ? Math.pow(2, exponent) : 1);
     42 }