Skip to content

Instantly share code, notes, and snippets.

@ozio
Created February 15, 2023 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozio/4fb766cfc1808f066b959614762f03f0 to your computer and use it in GitHub Desktop.
Save ozio/4fb766cfc1808f066b959614762f03f0 to your computer and use it in GitHub Desktop.
Yandex AA tasks
/**
* Дан список целых чисел, повторяющихся элементов в списке нет.
* Нужно преобразовать это множество в строку,
* сворачивая соседние по числовому ряду числа в диапазоны.
*/
compress([1, 4, 5, 2, 3, 9, 8, 11, 0]) // '0-5,8-9,11'
compress([1, 4, 3, 2]) // '1-4'
compress([1, 4]) // '1,4'
compress([1, 2]) // '1-2'
function compress(list) {
const sortedList = list.sort((a, b) => a - b)
const groups = []
let firstValue
let currentValue
for (let i = 0; i < sortedList.length; i++) {
if (typeof firstValue === 'undefined') {
firstValue = sortedList[i]
}
currentValue = sortedList[i]
if (typeof sortedList[i + 1] === 'undefined' || sortedList[i + 1] - currentValue > 1) {
groups.push(firstValue + (currentValue !== firstValue ? '-' + currentValue : ''))
firstValue = undefined
}
}
return groups.join(',')
}
///
/*
Дан массив ссылок: ['url1', 'url2', ...] и лимит одновременных запросов (limit)
Необходимо реализовать функцию, которая опросит урлы и вызовет callback c массивом ответов
['url1_answer', 'url2_answer', ...] так, чтобы в любой момент времени выполнялось не более limit
запросов (как только любой из них завершился, сразу же отправляется следующий)
Т.е. нужно реализовать шину с шириной равной limit.
Требования:
- Порядок в массиве ответов должен совпадать с порядком в массиве ссылок
Дополнительно:
- Функция должна обладать мемоизацией (один и тот же урл не опрашивать дважды)
Для опроса можно использовать fetch или $.get
Ошибки обрабатывать не нужно
*/
// declare function fetch(url: string): Promise<string>;
// declare function $.get(url: string, callback: (res: string) => void): void;
function parallelLimit(urls, limit, callback) {
const results = []
const memo = {}
let currentIndex = 0
let pendingCount = 0
const agent = (index) => {
currentIndex += 1
pendingCount += 1
const fn = (json) => {
results[index] = json
memo[urls[index]] = index // a
pendingCount--
if (urls[currentIndex]) {
agent(currentIndex)
}
if (pendingCount === 0) {
callback(results)
}
}
if (memo[urls[index]] ) {
fn(results[index])
} else {
fetch(urls[index]).then(res => res.json()).then(fn)
}
}
for (let i = 0; i < Math.min(limit, urls.length); i++) {
agent(i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment