'*'
в качестве результата, реально вы выдаёте '*\n'
..join('\n')
. Ну и ещё пробелов не хватает после звёздочек.const christmasTree = length =>
Array.from({ length }, (n, i) => (
n = ' '.repeat(length - i - 1),
n + '*'.repeat(i * 2 + 1) + n
)).join('\n');
const random = arr => arr[Math.random() * arr.length | 0];
const item = random(random(Object.values(state.themes)));
const item = random(Object.values(state.themes).flat());
function weightedRandom(arr, key = () => 1) {
const val = key instanceof Function ? key : n => n[key];
const max = arr.reduce((acc, n) => acc + val(n), 0);
return () => {
let rand = Math.random() * max;
return arr.find(n => (rand -= val(n)) < 0);
};
}
const randomArr = weightedRandom(Object.values(state.themes), 'length');
// ...
const item = random(randomArr());
const elements = Array.prototype.filter.call(
document.querySelectorAll('.green'),
(n, i, a) => n.nextElementSibling !== a[i + 1]
);
'.green + .green'
, или при фильтрации дополнительно проверяйте, что n.previousElementSibling === a[i - 1]
. str.split('/').pop()
// или
str.match(/[^\/]+$/)[0]
// или
str.replace(/.*\//, '')
// или
str.slice(str.lastIndexOf('/') + 1)
// или
Array.from(str).reduce((acc, n) => n === '/' ? '' : acc + n, '')
// или
[...str].filter((n, i, a) => !a.includes('/', i)).join('')
const getTruthyKeys = obj =>
Object
.entries(obj)
.filter(n => n[1])
.map(n => n[0]);
for([key, value] of Object.entries(item)) {
const obj = new Proxy({
a: 0,
b: 1,
c: 2,
}, {
get: () => Math.round(Math.random()),
});
console.log(Array.from({ length: 10 }, () => getTruthyKeys(obj)));
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.')
);
$('.content_toggle').click(function() {
const $button = $(this);
$(`#box-${this.id.split('-').pop()}`).slideToggle(300, function() {
const isHidden = $(this).is(':hidden');
$button
.text(isHidden ? 'Показать текст' : 'Скрыть текст')
.toggleClass('open', !isHidden);
});
return false;
});
$(this).closest('здесь селектор общего предка').find('.content_block')
$(this).next()
$('.content_block').eq($('.content_toggle').index(this))
$(document).on('click', 'a[id^="answer_"]', e => $(`#comment_${e.target.id}`).toggle());
function setNestedVal(root, path, val) {
const keys = path.split('.');
const key = keys.pop();
keys.reduce((acc, n) => acc[n] ??= {}, root)[key] = val;
}
setNestedVal(data, '0.arr.0.str', 'hello, world!!');
setNestedVal(data, '0.arr.1.num', 666);
Интересуют готовые решения
Нужно изменить этот массив, преобразовав все строки с датами в нём, независимо от того, как глубоко они вложены, в объекты.
const replaceValues = (data, test, transform) =>
test(data)
? transform(data)
: data instanceof Array
? data.map(n => replaceValues(n, test, transform))
: data instanceof Object
? Object.fromEntries(Object
.entries(data)
.map(([ k, v ]) => [ k, replaceValues(v, test, transform) ])
)
: data;
const newData = replaceValues(
data,
x => typeof x === 'string' && /^\d{2}\.\d{2}\.\d{4}$/.test(x),
str => new Date(str.split('.').reverse().join('-'))
);
const sum = arr.reduce((acc, n) => acc + n.number, 0);
const newArr = arr.map(n => ({ ...n, percent: n.number / sum * 100 }));
Object
.entries(arr.reduce((acc, n) => (
n = n.match(/('.*?'):'(.*?)'/),
(acc[n[1]] ??= []).push(n[2]),
acc
), {}))
.map(n => `${n[0]}:'${n[1].join('|')}'`)
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.3.4/cdn.min.js"></script>
<div x-data="{
items: [
{ id: 69, text: 'hello, world!!' },
{ id: 187, text: 'fuck the world' },
{ id: 666, text: 'fuck everything' },
],
}">
<template x-for="(n, i) in items">
<div>
<span x-text="n.text"></span>
<button @click="items.splice(i, 1)">x</button>
</div>
</template>
</div>
Код, который работает некорректно...
Object.freeze
назначить новое свойство уже не получится. Можно записать итератор в прототип массива (ну и после того, как он отработает, вернуть оригинальный итератор на место):const originalIterator = Array.prototype[Symbol.iterator];
Array.prototype[Symbol.iterator] = function() {
let i = -1;
return {
next: () => (i += 2) < arr.length
? { done: false, value: this[i] }
: { done: true },
};
};
setTimeout(() => Array.prototype[Symbol.iterator] = originalIterator, 0);
const result = arr.flat();
// или
const result = Array.prototype.concat.apply([], arr);
// или
const result = arr.reduce((acc, n) => (acc.push(...n), acc), []);
// или
const result = [];
for (const n of arr) {
for (const m of n) {
result[result.length] = m;
}
}
document.querySelectorAll('.filter__item').forEach(n => {
n.style.display = Array
.from(n.querySelectorAll('.filter__checkgroup-count'))
.some(m => +m.innerText.trim())
? 'block'
: 'none';
});
.hidden {
display: none;
}
for (const n of document.getElementsByClassName('filter__item')) {
n.classList.toggle('hidden', Array.prototype.every.call(
n.getElementsByClassName('filter__checkgroup-count'),
m => Number(m.textContent.trim()) === 0
));
}
function isEqual(a, b) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(n => a[n] === b[n]);
}
const result = arr1.concat(arr2.filter(n => arr1.every(m => !isEqual(n, m))));
const unique = function(arr, keys = n => n) {
const picked = new Map;
return arr.filter((...args) => {
const p = []
.concat(keys(...args))
.reduce((acc, k) => acc.set(k, acc.get(k) ?? new Map).get(k), picked);
return !p.set(this, p.has(this)).get(this);
});
}.bind(Symbol());
const result = unique([ ...arr1, ...arr2 ], n => [ n.teamId, n.userId ]);
// если уверены, что длины всех массивов будут равны
const zip = arrs => arrs[0]?.map((n, i) => arrs.map(m => m[i])) ?? [];
// или, вместо отсутствующих значений подставляем какое-то дефолтное
const zip = (arrs, defaultValue = null) => Array.from(
{ length: Math.max(...arrs.map(n => n.length)) },
(n, i) => arrs.map(m => i < m.length ? m[i] : defaultValue)
);
// или
const zip = (arrs, defaultValue = null) =>
arrs.reduce((acc, n, i) => (
n.forEach((m, j) => (acc[j] ??= Array(arrs.length).fill(defaultValue))[i] = m),
acc
), []);
const arr = zip([ arr1, arr2 ]);
. const chunked = (arr, chunkSize) =>
arr.reduce((acc, n, i) => (
(i % chunkSize) || acc.push([]),
acc.at(-1).push(n),
acc
), []);
console.log(chunked([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], 3));
const group = (data, key) =>
Array.prototype.reduce.call(
data,
(acc, n, i, a) => ((acc[key(n, i, a)] ??= []).push(n), acc),
{}
);
const chunked = (data, chunkSize) =>
Object.values(group(data, (_, i) => i / chunkSize | 0));
console.log(chunked('0123456789', 3));
console.log(chunked(document.querySelectorAll('img'), 5));
const chunked = (data, chunkSize, slice = data.slice) =>
Array.from(
{ length: Math.ceil(data.length / chunkSize) },
function(_, i) {
return this(i * chunkSize, (i + 1) * chunkSize);
},
(slice instanceof Function ? slice : Array.prototype.slice).bind(data)
);
console.log(chunked('abcdefghij', 4)); // так кусками будут тоже строки
console.log(chunked('abcdefghij', 4, [].slice)); // а так - массивы
console.log(chunked($('img'), 5));
function* chunked(data, chunkSize) {
let chunk = [];
for (const n of data) {
if (chunk.push(n) === chunkSize) {
yield chunk;
chunk = [];
}
}
if (chunk.length) {
yield chunk;
}
}
console.log(Array.from(chunked([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], 3)));
console.log([...chunked(document.querySelectorAll('img'), 5)]);
for (const n of chunked(Array(10).keys(), 4)) {
console.log(n);
}