forked from fuqcool/node-stringify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode-stringify.js
More file actions
41 lines (32 loc) · 982 Bytes
/
node-stringify.js
File metadata and controls
41 lines (32 loc) · 982 Bytes
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
var _ = require('underscore')
function escapeString(str) {
return str
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\v/g, '\\v')
.replace(/[\b]/g, '\\b')
.replace(/\f/g, '\\f')
}
function stringify(obj) {
if (_.isNull(obj)) return 'null'
if (_.isUndefined(obj)) return 'undefined'
if (_.isRegExp(obj) || _.isNumber(obj) || _.isBoolean(obj))
return obj.toString()
if (_.isFunction(obj))
return '(' + obj.toString() + ')'
if (_.isString(obj))
return "'" + escapeString(obj) + "'"
if (_.isDate(obj)) return 'new Date(' + obj.getTime() + ')'
if (_.isArguments(obj))
obj = _.toArray(obj)
if (_.isArray(obj))
return '[' + _.map(obj, stringify).join(',') + ']'
if (_.isObject(obj))
return '({' + _.map(obj, function (v, k) {
return stringify(k) + ':' + stringify(v)
}).join(',') + '})'
}
module.exports = stringify