const combinations = (arr, num) => {
const result = [];
const comb = (arr, n, idx, cur) => {
for (let i = idx; i <= arr.length - n; i += 1) {
cur.push(arr[i]);
if (n === 1) {
result.push([...cur]);
} else {
comb(arr, n - 1, i + 1, cur);
}
cur.pop();
}
};
comb(arr, num, 0, []);
return result;
}
console.log(combinations([1, 2, 3, 4], 3));
// Array(4) [ (3) […], (3) […], (3) […], (3) […] ]
// 0: Array(3) [ 1, 2, 3 ]
// 1: Array(3) [ 1, 2, 4 ]
// 2: Array(3) [ 1, 3, 4 ]
// 3: Array(3) [ 2, 3, 4 ]
// length: 4
const makeTimes = (interval, elapsedTimeMin) => {
const deltaTimeMin = Math.ceil(elapsedTimeMin / 30) * 30;
const startTime = new Date(interval.start);
const endTime = new Date(interval.end);
if (startTime.getSeconds() > 0) {
startTime.setSeconds(60);
}
startTime.setMinutes(Math.ceil(startTime.getMinutes() / 30) * 30);
const result = [];
while (startTime <= endTime) {
result.push(startTime.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }));
startTime.setMinutes(startTime.getMinutes() + deltaTimeMin);
}
return result;
}
makeTimes({start: 'Tue Aug 30 2022 09:00:00', end: 'Tue Aug 30 2022 16:30:00'}, 20);
// Array(16) [ "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", … ]
makeTimes({start: 'Tue Aug 30 2022 09:00:00', end: 'Tue Aug 30 2022 16:30:00'}, 40);
// Array(8) [ "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00" ]
const replaces = {
zero: '0',
one: '1',
two: '2',
plus: '+',
minus: '-',
};
const wordedMath = (expr) => {
const re = RegExp(`(${Object.keys(replaces).join('|')})`, 'g');
const value = eval(
expr.toLowerCase().replaceAll(re, (s) => replaces[s])
);
return Object.keys(replaces).find((e) => replaces[e] == value) ?? value;
}
Promise.all(
URL.map(
(url) => fetch(url)
.then((response) => `${url} : ${response.status} ${response.statusText}`)
.catch((e) => `${url} : ${e.message}`),
),
)
.then(
(results) =>
alert(results.join("\n")),
);
var unresolved = URL.length;
var results = [];
for (i = 0; i < URL.length; i += 1) {
(function(i) {
var request = new XMLHttpRequest();
request.open("GET", URL[i]);
request.onreadystatechange = function (event) {
console.log(request);
if (request.readyState === 4) {
if (request.status === 200) {
results[i] = URL[i] + ' РАБОТАЕТ';
} else {
results[i] = URL[i] + ' НЕ РАБОТАЕТ';
}
unresolved -= 1;
console.log(unresolved);
if (unresolved === 0) {
alert(results.join("\n"));
}
}
}
request.send();
})(i);
}
Promise.resolve(value)
- это статический метод, возвращающий промис в состоянии fulfilled с указанным значением.new Promise((resolve) => resolve(value))
И можно как-то выполнить промис без аргументов?Что значит "выполнить"? Создать можно, сменить статус с pending на fulfilled нельзя, на rejected можно по исключению.
new Promise((แก้ไข) => แก้ไข('Решено'));
//Promise { <state>: "fulfilled", <value>: "Решено" }
const text = 'Текст для сохранения';
const blob = new Blob([text], { type: 'text/plain' });
const content = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = content;
link.download = 'test.txt';
document.body.appendChild(link);
const click = new Event('click');
link.dispatchEvent(click);
link.remove();
const str = "{'id':'147','name':'example's name1','address':'sample street 1'}";
const [_, id, name, address] = str.match(/{'id':'(.*?)','name':'(.*?)','address':'(.*?)'}/);
console.log(id); // 147
console.log(name); // example's name1
console.log(address); // sample street 1
const re = /{'id':'(?<id>.*?)','name':'(?<name>.*?)','address':'(?<address>.*?)'}/;
const result = re.exec("{'id':'147','name':'example's name1','address':'sample street 1'}");
console.log(result.groups);
// Object { id: "147", name: "example's name1", address: "sample street 1" }
const increaseSalary = async () => {
try {
const employees = await api.getEmployees();
const employee = employees.reduce(
(acc, cur) => (acc.salary > cur.salary ? cur : acc),
{ salary: Infinity },
);
const newSalary = (employee.salary * 1.2) | 0;
const result = await api.setEmployeeSalary(employee.id, newSalary);
if (result.salary !== newSalary) {
throw 'API Error, salary has not increased';
}
await api.notifyEmployee(
employee.id,
`Hello, ${employee.name}! Congratulations, your new salary is ${newSalary}!`,
);
return true;
} catch (e) {
api.notifyAdmin(e.message);
return false;
}
});