'function to generate n length m depth data
I am trying to generate tree structure data, the problem is in helper function where I have an empty array children in which I want to push object with data, but get undefined
I do not get undefined when test it separately.
let b = {x: 1}
let a = []
a.push(b)
console.log(a)
function forestMockDataGenerator(n, m) {
const chance = new Chance(Math.random());
const mock = Array.from(Array(n).keys());
return mock.map(function (tree) {
tree = {
datum: chance.name(),
children: [],
};
return helper(tree, 1);
function helper(mock, count) {
if (isCountNotEqualToM(count, m)) {
mock.children.push({
datum: equalOneAddressEqualTwoPhone(count),
children: [],
});
helper(mock.children, (count = count + 1));
}
function equalOneAddressEqualTwoPhone(count) {
return count === 1 ? chance.address() : chance.phone();
}
function isCountNotEqualToM(count, m) {
return count !== m ? true : false;
}
return mock;
}
});
}
the data should have the next format
[
{
"name": "String",
"children": [
{
"name": "String",
"children": [
// ...
]
}, {
"name": "String",
"children": [
// ...
]
},
// ...
]
}, {
"name": "String",
"children": [
// ...
]
},
// ...
]
Solution 1:[1]
You yould use independent creation of children by handing over the decremented depth.
function forestMockDataGenerator(n, m) {
if (!m) return [];
return Array.from({ length: n }, (_, i) => ({
name: `name${i}`,
children: forestMockDataGenerator(n, m - 1),
}));
}
console.log(forestMockDataGenerator(5, 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nina Scholz |
