Last active
August 11, 2018 20:14
-
-
Save manjula-dube/5787ef0fb451d5c8b9b7703a29fecad9 to your computer and use it in GitHub Desktop.
This file contains 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 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Encode cyclic data structures.