const createTree = (data, index = []) =>
data.reduce((ul, { children: c }, i) => {
index.push(i);
const li = document.createElement('li');
li.innerText = index.join('_');
if (Array.isArray(c) && c.length) {
li.appendChild(createTree(c, index));
}
ul.appendChild(li);
index.pop();
return ul;
}, document.createElement('ul'));
// или
const createTree = (data, index = []) =>
data instanceof Array && data.length
? `<ul>${data.map((n, i) => `
<li>
${(index.push(i), index.join('_'))}
${createTree(n.children, index)}
${(index.pop(), '')}
</li>`).join('')}
</ul>`
: '';
X = n => n ? (n & 1 ? '-chirp' : '') + X(n >> 1) + X(n >> 1) : ''
chirp = n => X(n).slice(1)
function addChildrenIds(&$arr) {
$ids = [];
if (is_array($arr)) {
foreach ($arr as &$n) {
$n['childrenIds'] = addChildrenIds($n['children']);
array_push($ids, $n['id'], ...$n['childrenIds']);
}
}
return $ids;
}
const findPath = (obj, val) =>
Object.is(obj, val)
? []
: Object.entries(obj instanceof Object ? obj : {}).reduce((found, n) => {
if (!found) {
found = findPath(n[1], val);
if (found) {
found.unshift(n[0]);
}
}
return found;
}, null);
function findPath(obj, val) {
for (const stack = [ [ obj, [] ] ]; stack.length;) {
const [ n, keys ] = stack.pop();
if (Object.is(n, val)) {
return keys;
}
if (n instanceof Object) {
stack.push(...Object.entries(n).reverse().map(([ k, v ]) => [ v, [ ...keys, k ] ]));
}
}
return null;
}
const getReversedPaths = (arr, path = []) =>
arr.reduce((acc, { childItems, ...item }) => {
path.push(item);
if (childItems) {
acc.push(...getReversedPaths(childItems, path));
} else {
acc.push(path.length > 1
? path.map(({ packingLevel }, i, a) => ({ ...a[a.length - i - 1], packingLevel }))
: [ path[0] ]
);
}
path.pop();
return acc;
}, []);
const reverseThere = arr =>
getReversedPaths(arr).map(n =>
n.reduceRight((child, parent) => ({ ...parent, childItems: [ child ] }))
);
const reverseBackAgain = arr =>
(function createTree(arr) {
return Object.values(arr.reduce((acc, [ head, ...tail ]) => {
if (tail.length) {
(acc[head.name] = acc[head.name] || { ...head, childItems: [] }).childItems.push(tail);
} else {
acc[head.name] = head;
}
return acc;
}, {})).map(n => (n.childItems && (n.childItems = createTree(n.childItems)), n));
})(getReversedPaths(arr));
async function fetchRecursive(arr) {
const result = [];
if (Array.isArray(arr)) {
for (const n of arr) {
try {
result.push({ status: true, result: await fetch(n.url).then(r => r.json()) });
} catch(error) {
result.push({ status: false, error });
}
result.push(...await fetchRecursive(n.children));
}
}
return result;
}
const flat = arr => (arr || []).flatMap(n => [ n.url, ...flat(n.children) ]);
const fetchRecursive = arr => Promise.allSettled(flat(arr).map(n => fetch(n).then(r => r.json())));
const digital_root = num => num > 9
? digital_root([...`${num}`].reduce((acc, n) => acc + +n, 0))
: num;
function recursive(&$input) {
$closure = function(&$input) use (&$closure) {
foreach ($input as $key => &$value) {
if (is_array($value)) {
$closure($value);
} else {
echo $value;
}
}
};
$closure($input);
}
const createXML = obj => Object
.entries(obj)
.map(([ k, v ]) => `<ns1:${k}>${v instanceof Object ? createXML(v) : v}</ns1:${k}>`)
.join('');
const createXML = (obj, tabSize = 2, depth = 0) => {
const indent = ' '.repeat(tabSize * depth);
return Object.entries(obj).map(([ k, v ]) =>
indent +
`<ns1:${k}>${
v instanceof Object
? `\n${createXML(v, tabSize, depth + 1)}\n${indent}`
: v
}</ns1:${k}>`
).join('\n');
};
const findMin = obj =>
(obj.children || []).reduce((min, n) => (
n = findMin(n),
min.value < n.value ? min : n
), obj);
const count = obj =>
(obj.children || []).reduce((acc, n) => {
const c = count(n);
acc.num += c.num;
acc.sum += c.sum;
return acc;
}, { num: 1, sum: obj.value });
const c = count(obj);
const average = c.sum / c.num;
попытался решить все через рекурсию
const createTree = (data, idKey, parentKey, parentId) =>
data.reduce((acc, n) => (parentId === n[parentKey] && acc.push({
...n,
children: createTree(data, idKey, parentKey, n[idKey]),
}), acc), []);
const tree = createTree(data, 'id', 'parentId', null);
function createTree(data, idKey, parentKey) {
const tree = Object.fromEntries(data.map(n => [ n[idKey], { ...n, children: [] } ]));
return Object
.values(tree)
.filter(n => !(tree[n[parentKey]] && tree[n[parentKey]].children.push(n)));
}
const tree = createTree(data, 'id', 'parentId');
return
перед getSum(sum)
. const getWidths = data =>
[].concat(data || []).reduce((acc, n) => {
if (n.hasOwnProperty('width')) {
acc.push(n.width);
}
acc.push(...getWidths(n.columns));
return acc;
}, []);
const Comments = ({ items }) =>
Array.isArray(items) && items.length
? <React.Fragment>{items.map(n =>
<div className="comment" key={n.id}>
<h3>{n.name}</h3>
<div>{n.body}</div>
<Comments items={n.reply} />
</div>)}
</React.Fragment>
: null;
async function request(data) {
let result = data;
do {
result = await запрос(result);
} while (result не тот, который нужен);
return result;
}
function requestRecursive(data) {
return запрос(data).then(result => {
return result тот, который нужен
? result
: requestRecursive(result);
});
}
const getPrimitiveProps = (obj) =>
Object.entries(obj).reduce((acc, [ k, v ]) => ({
...acc,
...(v instanceof Object ? getPrimitiveProps(v) : { [k]: v }),
}), {});
const getPrimitiveProps = (obj) =>
Object.assign({}, ...Object.entries(obj).map(([ k, v ]) =>
v instanceof Object ? getPrimitiveProps(v) : { [k]: v }
));
function getRootItem($id, $array) {
foreach ($array as $item) {
if ($item['id'] === $id) {
$parent = $item['parent'];
return $parent === 0 ? $item : getRootItem($parent, $array);
}
}
return null;
}
function getUrls($parts, $acc = '') {
$urls = [];
if (count($parts)) {
$part = array_shift($parts);
if (!is_array($part)) {
$part = [ $part ];
}
foreach ($part as $p) {
array_push($urls, ...getUrls($parts, ($acc ? $acc.'/' : '').$p));
}
} else {
$urls[] = $acc;
}
return $urls;
}
$urls = getUrls($urlFragments);