Здесь я храню свои заметки и экспериментирую с кодом
📝 Заметки |
⭐ Любимые репозитории |
Задачи Яндекс.Контеста 2019 по направлению Frontend и мои решения на них
Home Page: https://contest.yandex.ru/
Здесь я храню свои заметки и экспериментирую с кодом
📝 Заметки |
⭐ Любимые репозитории |
Всем привет. Не знаю, правильно ли понял задачу. Может будут кейсы у вас.
const api = {
a: {
b: {
m: 1,
c: callback => setTimeout(() => callback(null, 'hello'), 100)
}
},
aa: {
bb: (callback, x, y) => setTimeout(() => callback(null, x + y), 200)
}
};
const handler = {
get(t, p) {
// Проверяю, есть ли какие-то данные по prop
if (t[p]) {
if (typeof t[p] === "object") {
return new Proxy(t[p], handler) // верну новую проксю, которая будет содержать такие же handler
}
if (typeof t[p] === "function") {
return (...args) => new Promise((r, e) => { // Забираю аргументы, их может быть множество
const callb = (error, data) => {
error ? e(error) : r(data); // тут получаю есть ли ошибка или всё хорошо
}
t[p](callb, ...args) // вызываю функцию с объекта.
} );
}
return t[p];
}
return undefined;
},
};
function promisify(api) {
return new Proxy(api, handler)
}
const promisedApi = promisify(api);
promisedApi.a.b.c()
.then(res => console.log(res)); // => ’hello’
promisedApi.aa.bb(1, 2)
.then(res => console.log(res));
console.log(promisedApi.a.b.m)
Какая тут логика.
Из объекта я делаю проксю (Это нужно чтобы решить пункт с тем, что апишка должна быть пасивной)
Далее если я получаю из объекта другой объект. Я даю ему хендлеры прокси и возвращаю новую проксю.
Если же я получил, что сейчас у меня функция, я возвращаю функцию с промимом. Жду от неё ответ и отправляю данные. Если это константа, тогда просто возвращаю константу
const searchers = [
["Mallory", "Everest", "Mont Blanc", "Pillar Rock"],
["Mawson", "South Pole", "New Hebrides"],
["Hillary", "Everest", "South Pole"]
];
function getToponim(arr) {
const allPoints = arr.reduce((acc, item) => {
acc = [...acc, ...item.slice(1)];
acc = Array.of(...new Set(acc))
return acc;
}, []);
const res = allPoints.map((point) => {
const searchersOnPoint = [];
searchers.forEach((searcher) => {
if (searcher.includes(point)) searchersOnPoint.push(searcher[0])
})
return [point, ...searchersOnPoint]
})
return res;
}
console.log(getToponim(searchers));
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.