const createTreeElement = (data, index = []) =>
Array.isArray(data) && data.length
? data.reduce((ul, n, i) => (
index.push(i),
ul.append(document.createElement('li')),
ul.lastChild.append(index.join('_'), createTreeElement(n.children, index)),
index.pop(),
ul
), document.createElement('ul'))
: '';
document.body.append(createTreeElement(data));const createTreeHTML = (data, index = '') =>
data instanceof Array && data.length
? `<ul>${data.map((n, i) => `
<li>
${(i = index + (index && '_') + i)}
${createTreeHTML(n.children, i)}
</li>`).join('')}
</ul>`
: '';
document.body.insertAdjacentHTML('beforeend', createTreeHTML(data));
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) =>
obj === val
? []
: Object.entries(obj instanceof Object ? obj : {}).reduce((found, n) => (
found || ((found = findPath(n[1], val)) && found.unshift(n[0])),
found
), null);function findPath(obj, val) {
for (const stack = [ [ obj, [] ] ]; stack.length;) {
const [ n, keys ] = stack.pop();
if (Object.is(n, val)) {
return keys;
} else if (n instanceof Object) {
stack.push(...Object.entries(n).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 createTree = (data, parentId = null) =>
data.reduce((acc, n) => (
parentId === n.parentId && (
acc[acc.length] = Object.assign(
{ children: createTree(data, n.id) },
n
)
),
acc
), []);function createTree({
data,
key = 'id',
parentKey = 'parentId',
childrenKey = 'children',
}) {
const tree = Object.fromEntries(data.map(n => [
n[key],
{ ...n, [childrenKey]: [] },
]));
return Object.values(tree).filter(n => !(
tree[n[parentKey]] && tree[n[parentKey]][childrenKey].push(n)
));
}
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);
const reverse = str =>
str.length < 2 ? str : reverse(str.slice(1)) + str[0];const reverse = ([ c, ...str ]) =>
c ? reverse(str) + c : '';