DISCLAIMER
Реализации сортировки могут быть разными.{ // выполнить в консоли браузера
const oneTest = () => {
let iterations = 0;
[1, 2, 3].sort((a, b) => {
const result = Math.random() > Math.random() ? 1 : -1;
console.log(`${iterations}: ${a} vs ${b} = ${result}`);
iterations++;
return result;
});
return iterations;
}
console.clear();
const totalTests = 10;
const stats = {};
for (let test = 0; test < totalTests; test++) {
console.group(`Test ${test + 1} of ${totalTests}`);
const iterations = oneTest();
stats[iterations] ??= 0;
stats[iterations]++;
console.groupEnd();
}
console.log(JSON.stringify(stats, null, 2));
}
$options = [
[null, $_LNG['TYPE_ORDER']],
['select_all', $_LNG['ALL_TYPES']],
['select_domain', $_LNG['DOMAIN']],
['select_server', $_LNG['SERVER']],
['select_ssl', $_LNG['SSL']],
['select_desing', $_LNG['DESING']],
['select_script', $_LNG['SCRIPT']],
['select_layout', $_LNG['LAYOUT']],
['select_adv', $_LNG['ADV']],
['select_seo', $_LNG['SEO']],
];
printf('const options = %s;', json_encode($options));
options
полноценный элемент select
со всеми опциями: createSelect = () => {
const select = document.createElement('select');
options.forEach(([value, title]) => {
const option = document.createElement('option');
option.innerText = title;
if (value) {
option.value = value;
} else {
option.setAttribute('disabled', true);
option.setAttribute('selected', true);
}
select.appendChild(option);
});
return select;
};
возвращает массив индексов элементов, у которые значение равно value.
const findIndex = (arr, value) => arr
.map((v, i) => ({ v, i }))
.filter(({ v }) => v === value)
.map(({ i }) => i);
Каждый элемент массива переделать в объект, где v
: элемент, а i
: индекс в массиве.бывш.элемент === value
i
setAttribute("disabled", true)
в зависимости от заполненности всех. Слушателем события "input" на каждом из полей вызывать эту функцию. const library = books.reduce((acc, c) => (acc[c.id] = c, acc), {});
const result = users.map(user => {
const books = user.books.map(id => library[id]);
return { ...user, books };
});
Codepen function addPointCenter(index) {
const avg = (a, b) => (a + b) / 2;
const midPoint = (p1, p2) => ({ lat: avg(p1.lat, p2.lat), lng: avg(p1.lng, p2.lng) });
const insert = (index, point) => latlng.splice(index, 0, point);
const { length } = latlng;
const current = latlng[index];
const indexLeft = (index - 1 + length) % length;
const pointLeft = midPoint(current, latlng[indexLeft]);
const indexRight = (index + 1) % length;
const pointRight = midPoint(current, latlng[indexRight]);
insert(index + 1, pointRight);
insert(index, pointLeft);
drawMarkers();
}
dot.str('qna.habr.com', 'value', this.data);
/* this.data:
{
qna: {
habr: {
com: "value"
}
}
} */
npm install dot-object --save
isLoading
, а свойство некого объекта изменять: flags.isLoading = false;
const PERIOD = 5000;
let timeout;
const action = () => {
console.log('Action!');
// this.switchNextTab()
clearTimeout(timeout);
timeout = setTimeout(action, PERIOD);
};
const flags = {
_isLoading: false,
set isLoading(value) {
this._isLoading = value;
if (!value) {
// isLoading стал false
action();
}
},
get isLoading() {
return this._isLoading;
},
};
timeout = setTimeout(action, PERIOD);
// где-то в коде:
flags.isLoading = true;
// ...
flags.isLoading = false; // тут же выполнится action
001
010
100
Из каждой цифры (0 или 1) делается ячейка таблицы. Строки оборачиваются в тег tr
, и всё это обёртывается в table. Полученный HTML вставляется в страницу. \b
для границы слова не работают, пришлось заглядывать впрёд-назад, и регулярка вышла некороткая.Object.entries(obj)
делает из объекта массив пар [[ключ, значение], ... ]
— [
[50: "3500"],
[100, "6000"],
...
]
const findRange = n => {
const obj = {
50: "3500",
100: "6000",
200: "8000",
300: "10500",
500: "13000",
501: "индивидуально"
};
const lookup = Object.entries(obj).sort(([a], [b]) => b - a);
return (lookup.find(([k, v]) => Number(k) <= n) ?? lookup.pop())[1];
};
findRange(49) // "3500"
findRange(99) // "3500"
findRange(100) // "6000"
findRange(500) // "13000"
findRange(501) // "индивидуально"
const state = {};
const getJSON = response => response.json();
getAuth()
.then(getJSON)
.then(({ id }) => {
state.id = id;
return getUser(id);
})
.then(getJSON)
.then(user => {
state.user = user;
})
.then(() => getOrder('users', state.id))
.then(getJSON)
.then(({ order }) => state.order = order)
.catch(console.error)
.finally(() => console.log("all done", state));
возможна ли реализация данной логики с помощью Promise.allSettled?
const state = {};
// подготовка
const getJSON = response => response.json();
const getUser = id =>
fetchUser(id)
.then(getJSON)
.then(({ user }) => (state.user = user));
const getOrder = id =>
fetchOrder('users', id)
.then(getJSON)
.then(({ order }) => (state.order = order));
// поехали
getAuth()
.then(getJSON)
.then(({ id }) => {
state.id = id;
return Promise.allSettled([getUser(id), getOrder(id)]);
})
.catch(console.error)
.finally(() => console.log('all done', state));
сtx.telegram
.sendPhoto(
ctx.chat.id,
ctx.message.photo[0].file_id,
{ caption: s, parse_mode: 'HTML', reply_markup: markup }
)
telegram.sendPhoto()
(исходник) передаётся через функцию fmtCaption()
(код) в api тележки, и доп. параметры помимо caption
должны пройти без изменений.