const addDepth = (val, depth = 0) =>
val instanceof Object
? Object.entries(val).reduce((acc, n) => (
acc[n[0]] = addDepth(n[1], depth + 1),
acc
), { depth })
: val;
return
перед gen_nums(stop_n, number)
?def gen_nums(max_num, num):
if num <= max_num:
print(num)
gen_nums(max_num, num + 1)
# или
def gen_nums(num):
if num >= 1:
gen_nums(num - 1)
print(num)
const getNestedData = (data, test) => Object
.values(data instanceof Object ? data : {})
.reduce((acc, n) => (
acc.push(...getNestedData(n, test)),
acc
), test(data) ? [ data ] : []);
const result = getNestedData(arr, n => n?.workControl?.includes?.('intermediate'));
function getNestedData(data, test) {
const result = [];
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (n instanceof Object) {
stack.push(...Object.values(n).reverse());
}
if (test(n)) {
result.push(n);
}
}
return result;
}
// или
function getNestedData(data, test) {
const result = [];
const stack = [];
for (let i = 0, arr = [ data ]; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
if (test(arr[i])) {
result.push(arr[i]);
}
if (arr[i] instanceof Object) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, Object.values(arr[i]) ];
}
}
}
return result;
}
tableValues(element);
element.children
/element.childNodes
.document.querySelector('form').childNodes
children
вместо childNodes
. Ну и погуглите, в чём между ними разница.if (element.nodeType == 1 && element.nodeName == 'INPUT' || element.nodeName == 'SELECT') {
nodeType
лишняя. Кроме того, вам не помешает разобраться с приоритетом выполнения операторов - nodeType
вы тут проверяете только для input'а.let result = [];
const getValues = el =>
el instanceof Element
? [ 'INPUT', 'SELECT' ].includes(el.tagName)
? [ el.value ]
: [...el.children].flatMap(getValues)
: [];
// или
const getValues = el =>
[ 'INPUT', 'SELECT' ].includes(el?.tagName)
? [ el.value ]
: [].flatMap.call(el.children ?? [], getValues);
const values = getValues(document.querySelector('form'));
const values = Array.from(document.querySelector('form').elements, n => n.value);
const getFromDOMNodes = (node, test, getVal) =>
node instanceof Node
? Array.prototype.reduce.call(
node.childNodes,
(acc, n) => (acc.push(...getFromDOMNodes(n, test, getVal)), acc),
test(node) ? [ getVal(node) ] : []
)
: [];
const values = getFromDOMNodes(
document.querySelector('form'),
node => [ 'INPUT', 'SELECT' ].includes(node.nodeName),
node => node.value
);
function getUrls($tree, $url = '') {
$urls = [];
foreach ($tree as $n) {
$newUrl = ($url ? $url.'/' : '').$n->url;
array_push($urls, $newUrl, ...getUrls($n->subcategories ?? [], $newUrl));
}
return $urls;
}
const getNestedItems = (data, test) =>
data instanceof Object
? Object.values(data).flatMap(n => getNestedItems(n, test))
: test(data) ? [ data ] : [];
const result = getNestedItems(obj, x => /^[A-Z]+$/.test(x)).join('');
const entries = Object.entries(obj); for (const entry of entries) { if (!isObject(entry)) { result = Object.assign(result, Object.fromEntries(entry)); } else return cloneDeep(entry);
function getDividers(num, divider) {
return num === 1
? []
: num % divider
? getDividers(num, divider + 1)
: [ divider, ...getDividers(num / divider, divider) ];
}
function showDividers(num) {
if (!Number.isInteger(num) || num < 2) {
throw 'fuck off';
}
console.log(`${num} = ${getDividers(num, 2).join(' * ')}`);
}
const replaceValues = (val, test, replacer) =>
val instanceof Array
? val.map(n => replaceValues(n, test, replacer))
: val instanceof Object
? Object.fromEntries(Object
.entries(val)
.map(([ k, v ]) => [
k,
test(k, v)
? replacer(v)
: replaceValues(v, test, replacer)
])
)
: val;
const newData = replaceValues(
data,
k => k.includes('Date'),
v => v.replace(/(\d+)-(\d+)-/, '$2.$1.')
);
const toCamelCase = val =>
val instanceof Array
? val.map(toCamelCase)
: val instanceof Object
? Object.fromEntries(Object
.entries(val)
.map(n => [
n[0].replace(/_+(.)/g, (m, g1) => g1.toUpperCase()),
toCamelCase(n[1]),
])
)
: val;
function getURLs($arr, $path = []) {
$urls = [];
foreach ($arr as $item) {
array_push($path, $item['slug']);
array_push($urls, '/'.implode('/', $path).'/', ...getURLs($item['children'], $path));
array_pop($path);
}
return $urls;
}
const deleteTextNodes = el =>
el.nodeType === Node.TEXT_NODE
? el.remove()
: [...el.childNodes].forEach(deleteTextNodes);
Как можно дополнить мой код, чтобы он проверял то, что требуется?
И можно как-нибудь без объявления переменной n внутри функции?
const getMaxDepth = arr =>
Array.isArray(arr)
? 1 + Math.max(0, ...arr.map(getMaxDepth))
: 0;
console.log(getMaxDepth([ 1, [ 2 ], [ [ 3 ] ], [ [ [ 4 ] ] ] ])); // 4
console.log(getMaxDepth([])); // 1
console.log(getMaxDepth(666)); // 0
const sum = (data, getVal) => Object
.values(data instanceof Object ? data : {})
.reduce((acc, n) => acc + sum(n, getVal), getVal(data));
sum([ 1, 2, 3, '1', [ '2', 4, [ '3' ] ], '4' ], x => +(typeof x === 'string')) // 4
sum({ a: { b: [ NaN, Infinity ], c: 123456 } }, x => +(typeof x === 'number')) // 3
function xxx(key) {
let val = entityTree[key];
const nextKey = Array.isArray(val) && (val = [...val], val.pop());
return val ? [].concat(key, val, xxx(nextKey)) : [];
}
mass
передавайте mass.copy()
.