Skip to content

Instantly share code, notes, and snippets.

@shenron
Created October 2, 2019 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shenron/f98364148936383529d2dd7890326849 to your computer and use it in GitHub Desktop.
Save shenron/f98364148936383529d2dd7890326849 to your computer and use it in GitHub Desktop.
Stringify Data - recursive function
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`);
}
@tcastelly
Copy link

tcastelly commented Oct 2, 2019

Without use output param:

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 = '') => {
   let res;
   if (Array.isArray(params)) {
     res = params.map((p, i) => recursiveParse(p, `${parent}(${i})`));
   } else if (typeof params === 'object') {
     res = Object.keys(params).map(k => recursiveParse(params[k], parent ? `${parent}.${k}` : k));
   } else {
     res = [`${parent} := ${params}`];
   }

   return res.reduce((acc, val) => acc.concat(val), []);
}

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