aboutsummaryrefslogtreecommitdiff
path: root/node_modules/es5-ext/json/safe-stringify.js
blob: f2562541af152cc122d3f26d864ff9b39d51ea92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"use strict";

var compact   = require("../array/#/compact")
  , isObject  = require("../object/is-object")
  , toArray   = require("../object/to-array")
  , isArray   = Array.isArray
  , stringify = JSON.stringify;

module.exports = function self (value /*, replacer, space*/) {
	var replacer = arguments[1], space = arguments[2];
	try {
		return stringify(value, replacer, space);
	} catch (e) {
		if (!isObject(value)) return null;
		if (typeof value.toJSON === "function") return null;
		if (isArray(value)) {
			return (
				"[" +
				compact.call(
					value.map(function (item) {
						return self(item, replacer, space);
					})
				) +
				"]"
			);
		}
		return (
			"{" +
			compact
				.call(
					toArray(value, function (item, key) {
						item = self(item, replacer, space);
						if (!item) return null;
						return stringify(key) + ":" + item;
					})
				)
				.join(",") +
			"}"
		);
	}
};