const results = Object.values(arr.reduce((acc, c) => {
const prefix = c.id.split('.')[0];
acc[prefix] = [...acc[prefix] ?? [], c];
return acc;
}, {})
);
/* [
[{"id":"0"},{"id":"0.0"},{"id":"0.1"},{"id":"0.2"},{"id":"0.3"}],
[{"id":"1"},{"id":"1.0"},{"id":"1.1"}],
[{"id":"2"},{"id":"2.0"},{"id":"2.1"},{"id":"2.2"}],
] */
isDone
(true / false).const getLeaders = numbers =>
numbers.reduceRight(
(acc, c) => { // acc – аккумулятор, c – очередной элемент массива
if (c > acc.sum) { // если больше суммы тех, что правее
acc.result.unshift(c); // положить в массив результатов
}
acc.sum += c; // накапливать сумму
return acc; // аккумулятор пойдёт в следующую итерацию
},
{ result: [], sum: 0 } // начальное значение acc
)
.result; // в итоге интересует только массив result
// использование
getLeaders([16, 17, 5, 4, 3, 1]) // [ 17, 3, 1 ]
const arrA = a[0].trim().split("\n");
// [ "123", "1234", "12345", "123456" ]
const arrB = b[0].trim().split("\n");
// [ "a", "b", "c", "d" ]
const arrAB = arrA.map((str, index) => `${arrB[index]}: ${str}`);
// [ "a: 123", "b: 1234", "c: 12345", "d: 123456" ]
arrAB.join("\n")
/*
"a: 123
b: 1234
c: 12345
d: 123456"
*/
const a = ['123', '1234', '12345', '123456'];
const b = ['a', 'b', 'c', 'd'];
const replace = (search, a, b) => {
const result = a.slice(); // копия
const index = a.indexOf(search);
if (index > -1) result.splice(index, 1, b[index]);
return result;
}
replace('1234', a, b)
// [ "123", "b", "12345", "123456" ]
async requestToSuip(suip, num_oper = '') {
const exampleData = {
result: false,
requisite: "",
amount: 0,
created: null,
suip: null
};
const url1 = "http://api-1/sber/cashout/suip/" + suip;
const url2 = "http://api-2/sber/cashout/txnid/" + num_oper;
const {data: data1} = await axios.get(url1);
const isEqual = Object.keys(exampleData)
.every(prop => exampleData[prop] === data1[prop]);
if (isEqual === false) {
return data1;
}
const {data: data2} = await axios.get(url2);
return {
...data1,
...data2, // поля из data2 перезапишут такие же из data1
};
}
function deep() {
function veryDeep() {
const inception = () => {
// во глубине сибирских руд:
globalThis.myGlobalVar = 'Habr'; // глобализм!
};
inception();
}
veryDeep();
}
deep();
console.log(myGlobalVar); // "Habr"
// random order in-place
const shuffle = array => {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[array[i], array[j]] = [array[j], array[i]];
}
};
// init
let coinIndex = -1;
const button = document.querySelector('.button');
button.addEventListener('click', () => {
if (coinIndex < 0) {
shuffle(coinFlip);
coinIndex = coinFlip.length - 1;
}
console.log(coinFlip[coinIndex]);
coinIndex--;
});
id
?const handleClick = id => () => {
document.querySelector('.container_wrp')?.remove();
const div = document.createElement('div');
div.style.width = '700px';
div.style.height = '500px';
div.id = id;
div.classList.add('container_wrp');
wrpBlock.appendChild(div);
};
jccBtnJap.addEventListener('click', handleClick('jap_container'));
jccBars.addEventListener('click', handleClick('stick_container'));
тут handleClick()
возвращает функцию, которая даёт создаваемому элементу переданный id. Thefor...in
statement iterates over all enumerable properties of an object
that are keyed by strings
(ignoring ones keyed by Symbols),
including inherited enumerable properties.
const m = new Map();
m.set({}, 'obj');
m.set('a', 'A');
// это другое
m.b = 'B';
for (let prop in m) {
console.log('property', prop);
}
// property b
open -n "/Applications/Calculator.app"
– каждое выполнение запустит новую копию Калькулятора для примера.import produce from "immer"
const nextState = produce(this.state, draft => {
// тут можно всё менять, не беспокоясь об иммутабельности
const { catValue } = draft;
catValue.cat.colors = Color.BLACK;
});
this.setState(nextState);
import produce from "immer"
const { catValue } = this.state;
const nextCatValue = produce(catValue, draft => {
// тут можно всё менять, не беспокоясь об иммутабельности
catValue.cat.colors = Color.BLACK;
});
this.setState({ catValue: nextCatValue });
cloneNode()
сработает только если слушатели прописаны прямо в атрибутах элемента <a onclick="alert('Habr')">click me</a>
addEventListener()
скопировать можно примерно никак.function myClickHandler(event) {
// что-то сделать по поводу клика
}
element1.addEventListener('click', myClickHandler);
element2.addEventListener('click', myClickHandler);
element3.addEventListener('click', myClickHandler);
<div id="parent">
<button>1</button>
<button>2</button>
<button>3</button>
</div>
и слушать клики на div#parent