Если нам нужно прокинуть данные от родителя к ребенку на сколь угодно глубокий уровень, мы можем воспользоваться provide/inject
, а если нам надо в обратную сторону?
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 getRandomPhotosArray = weightedRandom([
[ 9, truePhotos ],
[ 1, funnyPhotos ],
], 0);
function getPhoto() {
const photos = getRandomPhotosArray()[1];
return photos[Math.random() * photos.length | 0];
}
new ApexCharts(..., {
...
tooltip: {
...
y: {
title: {
formatter: (seriesName, seriesData) => ...,
},
formatter: (value, seriesData) => ...,
},
},
});
<div class="tab" @click="$router.push('/')">
router-link
. Там добавление класса уже реализовано, осталось только стили ему прописать. const getFromTree = (tree, childrenKey, getter = n => n) =>
Array.isArray(tree)
? tree.flatMap(n => [
getter(n),
...getFromTree(n[childrenKey], childrenKey, getter),
])
: [];
// или
function* flatTree(tree, childrenKey) {
if (
tree instanceof Object &&
tree[Symbol.iterator] instanceof Function
) {
for (const n of tree) {
yield n;
yield* getFromTree(n[childrenKey], childrenKey);
}
}
}
const getFromTree = function(tree, childrenKey, getter = n => n) {
const result = [];
for (const stack = this(tree); stack.length;) {
const n = stack.pop();
result.push(getter(n));
stack.push(...this(n[childrenKey]));
}
return result;
}.bind(x => x instanceof Array ? [...x].reverse() : []);
// или
const flatTree = function*(tree, childrenKey) {
const stack = [];
for (let [ i, arr ] = this(tree); ++i < arr.length || stack.length;) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
yield arr[i];
stack.push([ i, arr ]);
[ i, arr ] = this(arr[i][childrenKey]);
}
}
}.bind(x => [ -1, x?.constructor === Array ? x : [] ]);
getFromTree(tree, 'children').forEach(n => console.log(n));
// или
for (const n of flatTree(tree, 'children')) {
console.log(n);
}
$values = array_combine(
array_column($example2, 'SECTION_ID'),
array_column($example2, 'VALUE')
);
$example3 = array_map(function($n) use($values) {
$n['VALUE'] = $values[$n['SECTION_ID']];
return $n;
}, $example1);
{
title: data.title,
deadLineTimestamp: new Date(data.deadLine).getTime(),
description: data.description,
}
function createTree({
data,
key = 'id',
parentKey = 'parentId',
childrenKey = 'children',
}) {
const tree = Object.fromEntries(data.map(n => [ n[key], { ...n } ]));
return Object.fromEntries(Object.entries(tree).filter(([ , n ]) => !(
tree[n[parentKey]] && ((tree[n[parentKey]][childrenKey] ??= {})[n[key]] = n)
)));
}
const tree = createTree({
data: arr,
key: 'uid',
parentKey: 'parentUID',
});
И со слотами, и без слотов, и как только не пытался уже.
menu.insertAdjacentHTML('beforeend', arr
.map(n => `<li>${n}</li>`)
.join('')
);
// или
menu.append(...arr.reduce((acc, n) => (
(acc[acc.length] = document.createElement('li')).textContent = n,
acc
), []));
// или
for (const n of arr) {
menu.appendChild(document.createElement('li'));
menu.lastChild.innerText = n;
}
// или
arr.forEach(n => {
const li = document.createElement('li');
li.insertBefore(new Text(n), null);
menu.insertBefore(li, null);
});
// или
(function add(i) {
if (i < arr.length) {
menu.insertAdjacentElement('beforeend', document.createElement('li'));
menu.children[~-menu.children.length].innerHTML = arr[i];
add(-~i);
}
})(0);
const teamNamesObj = Object.fromEntries(teamNames.map(n => [ n.id, n.name ]));
const eplWithNames = epl.map(n => ({ ...n, team_name: teamNamesObj[n.team_id] }));
epl.forEach(function(n) {
n.team_name = this[n.team_id];
}, teamNames.reduce((acc, n) => (acc[n.id] = n.name, acc), {}));
const countWithKey = (arr, key) => arr.filter(n => key in n).length;
console.log(countWithKey(arr, 'ключ'));
const sum = (data, val = n => n) =>
Array.prototype.reduce.call(
data,
(acc, n) => acc + val(n),
0
);
console.log(sum(arr, obj => obj.hasOwnProperty('ключ')));
sum([ 1, 2, 3 ]) // 6
), так и более сложные варианты. Например, есть массив, представляющий содержимое корзины с товарами (цена, количество), надо посчитать общую стоимость:const cart = [
{ price: 100, count: 5 },
{ price: 10, count: 6 },
{ price: 1, count: 7 },
];
const total = sum(cart, item => item.price * item.count); // 567
const likes = sum(document.querySelectorAll('.btn_like .btn__counter'), n => +n.innerText);
function Counter(data, key = n => n) {
const counted = new Map;
for (const n of data) {
const k = key(n);
counted.set(k, (counted.get(k) ?? 0) + 1);
}
return k => counted.get(k) ?? 0;
}
const keyExists = Counter(arr, obj => Object.hasOwn(obj, 'ключ'));
console.log(keyExists(true)); // смотрим, у скольких элементов массива ключ есть
console.log(keyExists(false)); // и у скольких нет
const str = 'hello, world!!';
const chars = Counter(str);
console.log(chars('h')); // 1
console.log(chars('!')); // 2
console.log(chars('x')); // 0
const persons = [
{ name: 'Вася', birthday: new Date('1999-05-22') },
{ name: 'Маша', birthday: new Date('2004-03-06') },
{ name: 'Катя', birthday: new Date('1976-05-15') },
{ name: 'Петя', birthday: new Date('1987-04-18') },
{ name: 'Коля', birthday: new Date('2000-01-01') },
{ name: 'Дима', birthday: new Date('2003-05-09') },
{ name: 'Миша', birthday: new Date('1996-02-29') },
{ name: 'Таня', birthday: new Date('1981-03-12') },
{ name: 'Олег', birthday: new Date('1992-08-24') },
];
const birthMonths = Counter(
persons,
({ birthday }) => birthday.toLocaleString('ru-RU', { month: 'long' })
);
console.log(birthMonths('май')); // в мае родилось три человека
console.log(birthMonths('март')); // в марте два
console.log(birthMonths('октябрь')); // а в октябре никто
function* naturalNumbers(n) {
for (let i = 1; i <= n; i++) {
yield i;
}
}
const numLengths = Counter(naturalNumbers(100), num => `${num}`.length);
console.log(numLengths(2)); // среди первых ста натуральных чисел - девяносто двухзначных
console.log(numLengths(3)); // и одно трёхзначное
console.log(numLengths(0)); // число из нуля знаков? - конечно же нет таких
function objToString(val, tabSize = 2, depth = 0, noIndent = false) {
const indent = ' '.repeat(tabSize * depth);
return (noIndent ? '' : indent) + (
val instanceof Array
? `[\n${val.map(n => objToString(n, tabSize, depth + 1)).join(',\n')}\n${indent}]`
: val instanceof Object
? `{\n${Object
.entries(val)
.map(n => n.map((m, i) => objToString(m, tabSize, depth + 1, i)).join(': '))
.join(',\n')}\n${indent}}`
: typeof val === 'string'
? `"${val}"`
: val
);
}
console.log(objToString({
numbers: [ 69, 187, 666 ],
strings: [ 'hello, world!!', 'fuck the world', 'fuck everything' ],
falsy_values: [ 0, '', NaN, false, null, undefined ],
object: { xxx: true, yyy: Infinity, zzz: { '!&$': [ [ [ -1 ] ] ] } }
}));