javascript
How to make OpenAPI generator typescript-axios support JavaScript
Sometimes there is a moment when you don't want or cannot use the default OpenAPI generator preset, but you need to import your API library package in your JavaScript project.
I'm talking about typescript-axios preset that generates only TS files. It forces you to use babel or other transpiler.
JS-TS issue
I suppose you store npm package in npm repository (public or private like Nexus).
If you import your generated package it can cause an error in ES imports:
Failed to compile with 1 errors This dependency was not found: * your-api-package in ./src/store/actions.js To install it, you can run: npm install —save your-api-package
So you either have to add TS support or change building process.
npm publish runs npm run build as preinstall hook.
That gives you a dist folder with all necessary JavaScript code so such package can be used in both TS and JS projects.
Build template
But when you publish such package all you get is this basic *.ts files in root without dist.
All you need is to add to package.json these lines:
'files': [ 'dist' ]
And then publish it.
But you cannot edit package.json every time you update your OpenAPI spec.
Consider you use Java stack and build all your libs with gradle. The secret is that you can override *.mustache templates that is used during code generation.
In this case you should copy and edit original template: https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache and place it in your gradle templates folder (i.e. .templates/libraries/TypeScriptAxios/package.mustache).
build.gradle example:
... def rootClientTemplateDir = '$rootDir/templates/libraries/TypeScriptAxios'.toString() ... tasks.register('generateClient', org.openapitools.generator.gradle.plugin.tasks.GenerateTask) { println 'Start generating client ${clientConf.artifactId}' inputSpec = clientConf.inputSpec def info = [ version: extractVersion(clientConf.inputSpec) ] generatorName = clientConf.generatorName outputDir = clientOutputDir configOptions = clientConf.extendedConfiguration configOptions['npmName'] = clientConf.artifactId configOptions['npmVersion'] = '${info.version}' templateDir = rootClientTemplateDir }
Чемпионат по программированию Яндекса: Фронтенд, Финал 2019
Чемпионат по программированию Яндекса: Фронтенд, Квалификация 2019
Все задачи квалификации чемпионата Яндекса по программированию
Все задачи Яндекс Блиц Фронт 2 — 2018
Страница мероприятия:
https://yandex.ru/promo/jobs/blitz/2018/frontend/index
Квалификация
Инопланетный календарь
Код, в котором есть ошибка
Картинка с заданной вариативностью
Предупреждения
Концерт оркестра
Расставляем по полочкам
Финал
Здесь могла быть ваша реклама
Сверстать макет
Злоключения Адольфа
Лабиринт
Капча
Робот для пулл-реквестов
Задачки для собеседования на фронтендера
Эти задачи встречаются довольно часто. Рекомендую обращать внимание не на решения, а на то как объясняется происходящее.
Что выведет консоль?
var b = {};
var c;
b.b = 1;
c = b;
c.b = 2;
console.log(b.b); // ?
console.log(c.b); // ?
—
var i = 10;
var array = [];
while (i--) {
array.push(function() {
return i + i;
});
}
console.log([
array[0](),
array[1](),
])
let x, { x: y = 1 } = { x }; y;
console.log(x, y);
Напишите функцию
console.log(sum(2)(3)) // 5
console.log(sum(2,3)) // 5
Напишите функцию, которая делает копию объекта
Напишите функцию, аналогичную методу Array.prototype.reduce()
Есть связанный список. Напишите функцию, которая его переворачивает задом наперёд
Полезные на практике
class Storage {
// ?
}
const StorageInst = new Storage();
StorageInst.push(1).push(2).export() // [1,2]
—
function huff(src) {
return ;
}
huff('AABCCCDD'); // '2AB3C2D
Синтетические задачи, оторванные от реальной жизни:
let a = 10
a += ++a + a++ + a++
console.log(a);
—
// как сделать чтобы результат был положительный?
console.log((a == 1) && (a == 2) && (a == 3)) // true
—
var y = 5;
var x = function(){
return y;
};
var z = function(t){
var y = 10;
return t();
};
console.log(z(x));
—
(function(x, f = () => x) {
var x;
var y = x;
x = 2;
return [x, y, f()];
})(1);
—
/*
* Complete the 'ItemCollector' class below.
* The print function will return a comma separated list of the brands.
* You have to make the print function work by only modifying the class.
*/
class ItemCollector {
get items() {
return ["Apple", "Orange", "Grapes", "Watermelon"];
}
// Write your code here
// End of your code
constructor() {
return this;
}
}
function print() {
return Array.from(new ItemCollector()).join(",");
}
Напишите функцию аналогичную JSON.stringify()
—
Иньекция зависимостей в компонентах Вью: способы решения.
Библиотека компонентов и возможные проблемы
Что делать когда переиспользуемый компонент нужно модифицировать в зависимости от места
Передача состояний между компонентами?
Обучающие материалы по JavaScript и программированию
- На канале КоДоджо рассказывают про ЭС6 и многое другое
- На гитхабе идет работа над переводом серии книг «Вы не знаете ДжаваСкрипт» Кайла Симпсона. Я уже принял участие. Присоединяйтесь!
- Книга Эдди Османи про паттерны для приложений на ДжаваСкрипт http://largescalejs.ru/ (https://addyosmani.com/resources/essentialjsdesignpatterns/book/)
- Прекрасный иллюстрированный каталог паттернов проектирования и советы по рефакторингу кода https://refactoring.guru/ru
- Пактическое руководство по алгоритмам и структурам данных https://bradfieldcs.com/algos/
RTL layout cross-browser element.scrollLeft issue solution
Sometimes there is a moment as you make horizontal scrolling slider or timeline and become aware of the real world around you.
Some people will figure out the difference in how browsers implements Element.scrollLeft property on right to left layout (dir=«rtl»).
Most browsers have an initial value of scrollLeft equal to zero and will increase its value as you scroll (IE/Edge).
But in Chrome initial value of scrollLeft depends on scroll width (!) and is reduced to zero as you scroll.
Next problem is that some browsers increase scrollLeft value (Chrome, IE/Edge) while others decrease it to make it negative (Safari and Firefox).
Here is simple and obvious solution
// get initial value
var initial = el.scrollLeft();
// try to scroll with negative value
el.scrollLeft(-1);
// check if browser sets scrollLeft to negative
if ( el.scrollLeft() < 0 ) {
// Safari, FF
el.scrollLeft(/* ... */);
} else {
if ( initial > 0 ){
// Chrome
el.scrollLeft(/* ... */);
} else {
// IE
el.scrollLeft(/* ... */);
}
}