Created
February 14, 2015 03:38
-
-
Save mbildner/2384d523efc04cf7e456 to your computer and use it in GitHub Desktop.
quick and dirty implementation of JSON.stringify in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function () { | |
'use strict'; | |
var UNSAFE_STR_REGEX = /[\n\r]+/; | |
var SUPPORTED_TYPES = [ | |
'array', | |
'object', | |
'boolean', | |
'string', | |
'number' | |
]; | |
function contains (array, item) { | |
return array.indexOf(item) !== -1; | |
} | |
function getType (obj) { | |
var type = Array.isArray(obj) ? 'array' : typeof obj; | |
if (contains(SUPPORTED_TYPES, type)) { | |
return type; | |
} | |
else { | |
throw new TypeError('only types: <' + SUPPORTED_TYPES.join(',') + '> are supported'); | |
} | |
} | |
function isFunction (obj) { | |
return typeof obj === 'function'; | |
} | |
function stringify (obj) { | |
var str; | |
var keys; | |
var noFuncKeys; | |
switch (getType(obj)) { | |
case 'string': | |
str = '"' + obj.replace(UNSAFE_STR_REGEX, '') + '"'; | |
break; | |
case 'boolean': | |
str = '"' + obj.toString() + '"'; | |
break; | |
case 'number': | |
str = obj.toString(); | |
break; | |
case 'array': | |
str = '[' + obj.map(stringify).join(', ') + ']'; | |
break; | |
default: | |
keys = Object.keys(obj); | |
noFuncKeys = keys.filter(function (k) { | |
return !isFunction(obj[k]); | |
}); | |
str = '{' + noFuncKeys.map(function (k) { return stringify(k) + ':' + stringify(obj[k]); }) + '}'; | |
break; | |
} | |
return str; | |
} | |
if (module && module.exports) { | |
module.exports = stringify; | |
global.stringify = stringify; | |
} | |
else { | |
this.stringify = stringify; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment