Created
October 2, 2019 13:43
-
-
Save shenron/f98364148936383529d2dd7890326849 to your computer and use it in GitHub Desktop.
Stringify Data - recursive function
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 p = { | |
larr_dtls: [{ | |
id: 0, | |
arr_allocs: [{ | |
lots: 41, | |
tp: 'hedge', | |
phys_exec_id: 35, | |
}] | |
}, { | |
id: 1, | |
arr_allocs: [{ | |
lots: 42, | |
tp: 'hedge (2)', | |
phys_exec_id: 36, | |
}] | |
}] | |
}; | |
const recursiveParse = (params, parent, output) => { | |
if(!parent) { | |
parent = ''; | |
} | |
if(!output) { | |
output = []; | |
} | |
if (Array.isArray(params)) { | |
params.forEach((p, i) => { | |
recursiveParse(p, `${parent}(${i})`, output,) | |
}); | |
} else if (typeof params === 'object') { | |
Object.keys(params).forEach((k) => { | |
recursiveParse(params[k], parent ? `${parent}.${k}` : k, output); | |
}); | |
} else { | |
output.push(`${parent} := ${params}`); | |
} | |
return output; | |
} | |
const expected = [ | |
'larr_dtls(0).id := 0', | |
'larr_dtls(0).arr_allocs(0).lots := 41', | |
'larr_dtls(0).arr_allocs(0).tp := hedge', | |
'larr_dtls(0).arr_allocs(0).phys_exec_id := 35', | |
'larr_dtls(1).id := 1', | |
'larr_dtls(1).arr_allocs(0).lots := 42', | |
'larr_dtls(1).arr_allocs(0).tp := hedge (2)', | |
'larr_dtls(1).arr_allocs(0).phys_exec_id := 36', | |
]; | |
const res = recursiveParse(p); | |
for (let i = 0; i < expected.length; i += 1) { | |
console.log(res[i] === expected[i] ? `${i}: Correct` : `${i}: wrong`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without use
output
param: