JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" value="depth = 20" /> <input type="button" value="depth = 200" /> <input type="button" value="depth = 2000" />
JavaScript
function getEmails1(value) {
if (typeof value === 'string') {
return [value];
}
return Object.values(value).flatMap(getEmails1);
}
function getEmails2(value) {
const ret = [];
function getEmailsRec(v) {
if (typeof v === 'string') {
ret.push(v);
} else {
Object.values(v).forEach(getEmailsRec);
}
}
getEmailsRec(value);
return ret;
}
function run(e) {
const depth = parseInt(e.target.value.replace(/\D/g, ''));
const data = Array.from({
length: depth
}).reduce((v, u, i) => ({
a: 'a',
b: 'b',
c: 'c',
d: 'd',
e: 'e',
next: v
}), []);
const ts1 = performance.now();
getEmails1(data);
const d1 = performance.now() - ts1;
const ts2 = performance.now();
getEmails2(data);
const d2 = performance.now() - ts2;
alert('duration1 = ' + d1 + '\nduration2 = ' + d2 + '\nd1/d2 = ' + (d1/d2));
}
document.querySelectorAll('input').forEach(btn => { btn.onclick = run; });