Created
September 13, 2019 06:05
-
-
Save adit-hotstar/e1ca5d317b8a42b549a35aff9e244a17 to your computer and use it in GitHub Desktop.
Haskell style JSON stringification.
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
const stringify = (json, indent = 0) => { | |
if (json === null || typeof json !== 'object') return JSON.stringify(json); | |
const indentation = `\n${' '.repeat(indent)}`; | |
if (Array.isArray(json)) { | |
const { length } = json; | |
if (length === 0) return '[]'; | |
let result = `[ ${stringify(json[0], indent + 2)}`; | |
for (let i = 1; i < length; i += 1) { | |
result += `${indentation}, ${stringify(json[i], indent + 2)}`; | |
} | |
return `${result}${indentation}]`; | |
} | |
const toString = ([key, val]) => { | |
const result = val !== null && typeof val === 'object' | |
? `${indentation} ${stringify(val, indent + 2)}` | |
: ` ${JSON.stringify(val)}`; | |
return `${JSON.stringify(key)}:${result}`; | |
}; | |
const entries = Object.entries(json); | |
const { length } = entries; | |
if (length === 0) return '{}'; | |
let result = `{ ${toString(entries[0])}`; | |
for (let i = 1; i < length; i += 1) { | |
result += `${indentation}, ${toString(entries[i])}`; | |
} | |
return `${result}${indentation}}`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment