Created
June 23, 2022 20:25
-
-
Save ax2mx/ec68e39f22efaa0188c652a3175f0819 to your computer and use it in GitHub Desktop.
Simple object serializer
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 serialize = (obj) => { | |
| const type = typeof obj; | |
| if (obj === null) return 'null'; | |
| else if (type === 'string') return `'${obj}'`; | |
| else if (type === 'number') return obj.toString(); | |
| else if (type === 'boolean') return obj.toString(); | |
| else if (type !== 'object') return obj.toString(); | |
| else if (Array.isArray(obj)) { | |
| return `[${obj}]`; | |
| } else { | |
| let s = '{'; | |
| for (const key in obj) { | |
| const value = obj[key]; | |
| if (s.length > 1) s += ','; | |
| s += key + ':' + serialize(value); | |
| } | |
| return s + '}'; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment