From c6ea6cfd37881f3de8ea2b17917cc7fb1032b011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fredrik=20S=C3=B6derstr=C3=B6m?= Date: Fri, 16 Aug 2019 12:42:36 +0200 Subject: [PATCH 1/2] Add ES module version --- esm.js | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 esm.js diff --git a/esm.js b/esm.js new file mode 100644 index 0000000..bbbc25d --- /dev/null +++ b/esm.js @@ -0,0 +1,57 @@ +export default function stringify(data, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + const cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; + + const cmp = opts.cmp && (function (f) { + return function (node) { + return function (a, b) { + const aobj = { key: a, value: node[a] }; + const bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); + + const seen = []; + return (function stringifyNode(node) { + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } + + if (node === undefined) return; + if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; + if (typeof node !== 'object') return JSON.stringify(node); + + let i, out; + if (Array.isArray(node)) { + out = '['; + for (i = 0; i < node.length; i++) { + if (i) out += ','; + out += stringifyNode(node[i]) || 'null'; + } + return out + ']'; + } + + if (node === null) return 'null'; + + if (seen.indexOf(node) !== -1) { + if (cycles) return JSON.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } + + const seenIndex = seen.push(node) - 1; + const keys = Object.keys(node).sort(cmp && cmp(node)); + out = ''; + for (i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = stringifyNode(node[key]); + + if (!value) continue; + if (out) out += ','; + out += JSON.stringify(key) + ':' + value; + } + seen.splice(seenIndex, 1); + return '{' + out + '}'; + })(data); +} From 7a3dcf2e086222fcee52d354d50a6a80dea97aed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fredrik=20S=C3=B6derstr=C3=B6m?= Date: Fri, 16 Aug 2019 12:47:57 +0200 Subject: [PATCH 2/2] Add module defintion --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 1fbf1a4..b3db73f 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "version": "2.0.0", "description": "deterministic `JSON.stringify()` - a faster version of substack's json-stable-strigify without jsonify", "main": "index.js", + "module": "esm.js", "types": "index.d.ts", "dependencies": {}, "devDependencies": {