Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create jsonStringify.js #86

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions JavaScript/Programmes/jsonStringify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Online Javascript Editor for free
// Write, Edit and Run your Javascript code using JS Online Compiler
function isCyclic(input){
const seen = new Set()
function helper(value = input){
if(typeof value !== "object" || value === null){
return false
}
seen.add(value)
return Object.values(value).some((val) => seen.has(val) || helper(val))
}
return helper()
}

function jsonStringify(data){
const typeofData = typeof data
if(isCyclic(data)){
throw new TypeError('Converting circular structure to JSON');
}
if (typeof value === 'bigint') {
throw new TypeError('Do not know how to serialize a BigInt');
}
if(data === '' || data === undefined || typeofData === 'symbol' || typeofData === 'function'){
return undefined
}
if(data === null || data === Infinity || data === -Infinity || data !== data){
return 'null'
}
if(typeofData === "string"){
return `"${data}"`
}
if(typeofData === "number"){
return `'${data}'`
}
if(Array.isArray(data)){
const res = data.map(d => jsonStringify(d))
return `'[${res.join(',')}]'`
}
if(typeofData instanceof Date){
return `${data.toISOString()}`
}
if(typeofData === "object"){
const res = Object.entries(data).map(([key,val]) => {
// console.log(key,val)
if(val){
const d = jsonStringify(val)
return `"${key}":${d}`
}
}).filter(d => d !== undefined)
return `'{${res.join(',')}}'`
}
}

console.log(jsonStringify(() => {}))