Skip to content

Instantly share code, notes, and snippets.

@manjula-dube
Last active August 11, 2018 20:14
Show Gist options
  • Save manjula-dube/5787ef0fb451d5c8b9b7703a29fecad9 to your computer and use it in GitHub Desktop.
Save manjula-dube/5787ef0fb451d5c8b9b7703a29fecad9 to your computer and use it in GitHub Desktop.
const myArray = ['manjula','26','Software Engineer']
myArray[2] = myArray
const myArray1 = [ 1 , 'a' , { data : 'manjula'}]
myArray1[2].parent = myArray1
function encodeCycles(input) {
if(typeof input !== 'object') {
return input
}
const map = new WeakMap()
map.set(input, '$')
function encodeJSONCycle(obj, cleanedObj = {}, path = '') {
if(typeof obj !== 'object') {
return obj
}
for(var key in obj) {
if(key && typeof obj[key] === 'object') {
if(!map.get(obj[key])) {
map.set(obj[key], `${path}.${key}`)
cleanedObj[key] = encodeJSONCycle(obj[key], cleanedObj[key], `${path}${key}`)
} else {
cleanedObj[key] = { '$ref' : map.get(obj[key]) }
}
} else {
cleanedObj[key] = obj[key]
}
}
return cleanedObj
}
return encodeJSONCycle(input, input instanceof Array ? [] : {})
}
JSON.encodeCycles = encodeCycles
console.log('original input : ' , myArray ,'\nfinal output : ',
JSON.encodeCycles(myArray))
console.log("Stringify" + JSON.stringify(JSON.encodeCycles(myArray),'\t',4))
console.log('original input : ' ,
myArray1 ,'\nfinal output : ', JSON.encodeCycles(myArray1))
console.log("Stringify" + JSON.stringify(JSON.encodeCycles(myArray1),'\t',4))
console.log(JSON.encodeCycles(100))
@manjula-dube
Copy link
Author

Encode cyclic data structures.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment