randNum
содержит число.questFunc()
возвращает строку с текстом вопроса.people[`${questFunc()}`]
это, например, people["Это девушка?"]
– будет undefined
.people
не имеет строкового ключа. В нём два элемента с индексами 0 и 1.const questions = [
'Это самец?',
'Это девушка?',
'Носит очки?',
'Занимается спортом?',
'У этого человека смуглая кожа?',
];
const people = [
{ name: 'Егор', profile: [1, 0, 1, 1, 1] },
{ name: 'Залина', profile: [0, 1, 1, 1, 0] },
];
const questionElement = document.querySelector('.question');
let questionIndex; // индекс текущего вопроса
function askQustion() {
questionIndex = Math.floor(Math.random() * questions.length);
questionElement.innerHTML = questions[questionIndex];
return questions[questionIndex];
}
askQustion();
// TODO: принять ответ пользователя (true/false)
const answer = true; // допустим, ответил "да"
const candidates = people
.filter(({ profile }) => !!profile[questionIndex] === answer)
.map(({ name }) => name)
.join(', ');
console.log('Кандидаты:', candidates);
function randomDelay(min = 250, max = 750) {
return new Promise((resolve) => {
const ms = Math.random() * (max - min) + min;
setTimeout(resolve, ms);
});
}
function downloadAll(urls, limit = 4) {
return new Promise((resolveAll, rejectAll) => {
const result = [];
const iter = urls.entries();
let fulfilled = 0;
const next = () => {
const { done, value } = iter.next();
if (done) {
if (fulfilled === urls.length) {
resolveAll(result);
return;
}
return;
}
const [index, url] = value;
const onFulfilled = (val) => {
result[index] = val;
fulfilled += 1;
next();
};
randomDelay()
.then(() => fetch(url))
.then(onFulfilled, rejectAll);
};
for (let i = 0, l = Math.min(limit, urls.length); i < l; i++) {
next();
}
});
}
const urls = Array.from(
{ length: 100 },
(_, i) => `https://jsonplaceholder.typicode.com/todos/${i + 1}`
);
(async () => {
const responses = await downloadAll(urls, 2);
const data = await Promise.all(responses.map((r) => r.json()));
console.log(data);
})();
const N = 3;
const delay = ms => new Promise(res => setTimeout(res, ms));
const next = () => {
if (items.length > 0) {
return download(items.shift())
.then(delay(500 + Math.floor(Math.random() * 500))) // случайная пауза между закачками
.then(next);
}
};
const works = Array.from({ length: N }, () =>
Promise.resolve()
.then(next)
.catch(console.error)
);
Promise.all(works).then(() => console.log('All Done'));
а договора небыло. просто был прислан текстовый файл с заданием и я ответил что сделаю это.
б) а если "так", то будет "вот так".
const phones = [
{ p: '9171857450', c: 1 },
{ p: '9880735438', c: 10 },
{ p: '9880735439', c: 100 },
{ p: '9880735779', c: 2 },
{ p: '9170997305', c: 2 },
{ p: '9170997493', c: 2 },
{ p: '9880634879', c: 5 },
{ p: '9170996154', c: 1 },
{ p: '9880728447', c: 1 },
];
const chancesTotal = phones.reduce((acc, { c }) => acc + c, 0);
const selected = Math.floor(Math.random() * chancesTotal);
let phone;
for (let i = 0, sum = 0; i < phones.length; i++) {
sum += phones[i].c;
if (selected < sum) {
phone = phones[i].p;
break;
}
}
const randomUrl = `https://wa.me/${phone}?text=Привет!%20Пришлите%20мне%20цены%20на%20рыбку!`;
const makeDate = HHMM => {
const [H, M] = HHMM.split(':').map(Number);
const D = new Date();
D.setHours(H);
D.setMinutes(M);
D.setSeconds(0);
return D;
};
const oo = n => n.toString().padStart(2, '0'); // 5 => '05'
const fillTime = (startHHMM, finishHHMM, intervalMinutes) => {
let startDate = makeDate(startHHMM);
let finishDate = makeDate(finishHHMM);
if (startDate > finishDate) { // объекты Date можно так сравнивать
[startDate, finishDate] = [finishDate, startDate]; // поменять местами
}
const dates = [];
const D = new Date(startDate);
while (D <= finishDate) {
dates.push(new Date(D));
D.setMinutes(D.getMinutes() + intervalMinutes);
}
return dates.map(D => [D.getHours(), D.getMinutes()].map(oo).join(':'));
};
console.log(fillTime('15:56', '18:15', 17));
// [ "15:56", "16:13", "16:30", "16:47", "17:04", "17:21", "17:38", "17:55", "18:12" ]
const groupSum = (arr, idKey, ...sumKeys) =>
Object.values(arr.reduce((acc, n) => (
acc[n[idKey]] ??= sumKeys.reduce((group, k) => (
group[k] = 0,
group
), Object.assign(new n.constructor, n)),
sumKeys.forEach(k => acc[n[idKey]][k] += n[k]),
acc
), {}));
// ваш случай
const result = groupSum(arr, 'product', 'price', 'selling_price', 'quantity');
// элементам исходного массива не обязательно быть объектами, это могут быть и массивы
groupSum([
[ 'A', 1, 10 ],
[ 'A', 2, 20 ],
[ 'A', 3, 30 ],
[ 'B', 1, 5 ],
[ 'B', 10, 5 ],
[ 'B', 100, 5 ],
], 0, 1, 2) // [ [ 'A', 6, 60 ], [ 'B', 111, 15 ] ]
возвращает массив индексов элементов, у которые значение равно value.
const findIndex = (arr, value) => arr
.map((v, i) => ({ v, i }))
.filter(({ v }) => v === value)
.map(({ i }) => i);
Каждый элемент массива переделать в объект, где v
: элемент, а i
: индекс в массиве.бывш.элемент === value
i
const textDecoder = new TextDecoder('windows-1251');
const response = await fetch(...);
const buffer = await response.arrayBuffer();
const text = textDecoder.decode(buffer);
(async function() {
var result = await $.post('api/index.php', { raz: 'Привет, мир!' } );
console.log('Ответ сервера:', result);
})();
console.log
$_POST
<?php
header('Content-Type: text/plain; charset=UTF-8');
$json = json_encode($_POST, JSON_UNESCAPED_UNICODE);
file_put_contents('POST.json', $json);
echo 'Данные получены и записаны в файл POST.json -> смотри его.';
.hint
) пересекается с блоком А (основным текстом), и после, с использованием полученного и порогового (задаёте сами), можно решить, что делать с блоком.const clamp = (min, max, value) => Math.max(min, Math.min(max, value));
const calculateIntersection = (a, b) => {
const aRect = a.getBoundingClientRect();
const bRect = b.getBoundingClientRect();
const top = clamp(aRect.top, aRect.bottom, bRect.top);
const right = clamp(aRect.left, aRect.right, bRect.right);
const bottom = clamp(aRect.top, aRect.bottom, bRect.bottom);
const left = clamp(aRect.left, aRect.right, bRect.left);
const width = right - left;
const height = bottom - top;
const totalArea = bRect.width * bRect.height;
const intersectionArea = width * height;
const intersectionRatio = intersectionArea / totalArea;
return intersectionRatio;
};