This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Есть массив чисел | |
// Нужно выяснить есть ли в нем 2 числа сумма которых равна 18. | |
// сделать одним циклом | |
// два цикла O(n²) | |
function checkSum1(arr, sum = 18) { | |
for (let i = 0; i < arr.length; i++) { | |
for (let j = 0; j < arr.length; j++) { | |
if (j !== i && arr[i] + arr[j] === sum) { | |
return true; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// написать функцию банкомат, которая принимает на вход кол-во денег для возврата и лимиты купюр в банкомате | |
// должна вернуть объект с минимальным кол-вом купюр, чтобы разменять данный total | |
// перед возвратом значения, мы должны смутировать limits | |
// чтобы при последующем вызове функции atm, кол-во оставшихся купюр в банкомате изменилось | |
// если банкомат не может выдать сумму, то мутацию limits не делаем и возвращаем строку "cant change" | |
function atm(total, limits) { | |
const bills = Object.keys(limits) | |
.map(Number) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Дан массив банкнот определенных номиналов | |
// [1, 2, 5, 10, 20, 50], | |
// их количество не ограничено. | |
// Нужно выдать ему эти деньги используя минимальное количество купюр. | |
// reduceRight simple | |
const getCash1 = (bills, total) => { | |
let totalRemain = total; | |
return bills.reduceRight((acc, bill) => { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Есть парочка функций, которые необходимо запустить параллельно | |
// а результат вернуть только тогда, когда обе они будут завершены | |
const fnA = (cb) => { | |
setTimeout(() => { | |
cb("a"); | |
}, 3000); | |
}; | |
const fnB = (cb) => { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Нужно модифицировать метод fetch, | |
// добавив ему возможность автоматической переотправки запроса в случаи ошибки | |
const fetchMockReject = () => { | |
return new Promise((_, reject) => { | |
setTimeout(() => { | |
reject("timeout error"); | |
}, 1000); | |
}); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Нужно написать свой собственный метод debounce | |
function debounce(fn, timeout) { | |
let timeoutId = null; | |
return (...args) => { | |
clearTimeout(timeoutId); | |
timeoutId = setTimeout(() => { | |
if (typeof fn === "function") { | |
fn(...args); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Нужно написать функцию, которая проверит читается ли строка одинаково в обоих направлениях | |
// (без учета пробелов и знаков препинания) | |
// попробуйте решить несколькими способами | |
const isPalindrome1 = (str) => { | |
const punctuation = ' ,.;' | |
const arr = str.toLowerCase().split('') | |
.filter(ch => !punctuation.includes(ch)) | |
const reversedArr = arr.toReversed() | |
let result = true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// условия : | |
// если исчерпали попытки, то throw последнюю ошибку | |
// retryCount - количество попыток ретрая при не успехе | |
// timeoutMs - таймаут, если не успевает разрешиться промис, то абортим запрос | |
// 1 решение через рекурсию | |
// Если количество попыток (retryCount) будет очень большим, | |
// это может привести к переполнению стека вызовов, лучше использовать цикл | |
function retryFetch1(url, { retryCount, timeoutMs }) { | |
return new Promise((resolve, reject) => { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetchMock = (endpoint) => { | |
console.log("fetched --> " + endpoint); | |
// 'fetched' '/3000' | |
// 'fetched' '/error' | |
// 'fetched' '/2000' | |
// 'fetched' '/500' | |
// 'fetched' '/600' | |
const ms = Number(endpoint.slice(1)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetchMock = (delay) => { | |
return new Promise((resolve) => setTimeout(() => resolve(delay), delay)); | |
}; | |
const promiseAll = async (promises) => { | |
return new Promise((resolve, reject) => { | |
const results = []; | |
promises.forEach((promise) => { | |
promise | |
.then((res) => { |
NewerOlder