UNPKG

900 BJavaScriptView Raw
1import { factory } from '../utils/factory.js';
2var name = 'replacer';
3var dependencies = [];
4export 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});
\No newline at end of file