simple-squiggle

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

replacer.js (900B)


      1 import { factory } from '../utils/factory.js';
      2 var name = 'replacer';
      3 var dependencies = [];
      4 export var createReplacer = /* #__PURE__ */factory(name, dependencies, () => {
      5   /**
      6    * Stringify data types into their JSON representation.
      7    * Most data types can be serialized using their `.toJSON` method,
      8    * but not all, for example the number `Infinity`. For these cases you have
      9    * to use the replacer. Example usage:
     10    *
     11    *     JSON.stringify([2, Infinity], math.replacer)
     12    *
     13    * @param {string} key
     14    * @param {*} value
     15    * @returns {*} Returns the replaced object
     16    */
     17   return function replacer(key, value) {
     18     // the numeric values Infinitiy, -Infinity, and NaN cannot be serialized to JSON
     19     if (typeof value === 'number' && (!isFinite(value) || isNaN(value))) {
     20       return {
     21         mathjs: 'number',
     22         value: String(value)
     23       };
     24     }
     25 
     26     return value;
     27   };
     28 });