You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/03-code-quality/06-polyfills/article.md
+28-28Lines changed: 28 additions & 28 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -13,7 +13,7 @@
13
13
14
14
З іншого боку, як змусити працювати «сучасний» код на старих рушіях? Адже вони покищо не підтримують найновіших можливостей.
15
15
16
-
Для цього існує два інструменти:
16
+
Для цього існують два інструменти:
17
17
18
18
1. Транспілятори.
19
19
2. Поліфіли.
@@ -22,54 +22,54 @@
22
22
23
23
## Транспілятори
24
24
25
-
A [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler) is a special piece of software that translates source code to another source code. It can parse ("read and understand") modern code and rewrite it using older syntax constructs, so that it'll also work in outdated engines.
25
+
[Транспілятор](https://uk.wikipedia.org/wiki/Транскомпілятор) -- це спеціальний інструмент, який «перекладає» вихідний код з однієї мови програмування в код на іншій мові програмування. Також обробка коду може виконуватися в межах однієї мови програмування. Транспілятор парсить ("читає та розуміє") сучасний код і переписує його, використовуючи старі синтаксичні конструкції, які працюють на старих рушіях.
26
26
27
-
E.g. JavaScript before year 2020 didn't have the "nullish coalescing operator" `??`. So, if a visitor uses an outdated browser, it may fail to understand the code like`height = height ?? 100`.
27
+
Наприклад, JavaScript до 2020 року не мав "оператора об’єднання з null" `??`. Якщо відвідувач використовує старий браузер, він не зможе виконати код, на кшталт`height = height ?? 100`.
28
28
29
-
A transpiler would analyze our code and rewrite `height ?? 100`into`(height !== undefined && height !== null) ? height : 100`.
29
+
Транспілятор проаналізує такий код і перепише `height ?? 100`на`(height !== undefined && height !== null) ? height : 100`.
Now the rewritten code is suitable for older JavaScript engines.
39
+
Тепер, переписаний код буде коректно виконуватися на старих рушіях JavaScript.
40
40
41
-
Usually, a developer runs the transpiler on their own computer, and then deploys the transpiled code to the server.
41
+
Зазвичай, розробник запускає на своєму комп’ютері транспілятор разом з компілятором, а вже після цього розгортає ("деплоє" від слова deploy) код на сервер.
42
42
43
-
Speaking of names, [Babel](https://babeljs.io) is one of the most prominent transpilers out there.
43
+
Говорячи про імена, [Babel](https://babeljs.io) -- один з найвідоміших транспіляторів.
44
44
45
-
Modern project build systems, such as [webpack](http://webpack.github.io/), provide means to run transpiler automatically on every code change, so it's very easy to integrate into development process.
45
+
Сучасні збирачі проєктів, такі як [webpack](http://webpack.github.io/), надають засоби для автоматичного запуску транспілятора при кожній зміні коду, тому його дуже легко інтегрувати в процес розробки.
46
46
47
47
## Поліфіли
48
48
49
-
New language features may include not only syntax constructs and operators, but also built-in functions.
49
+
Серед нового функціоналу мови можуть бути не тільки синтаксичні конструкції та оператори, але й також вбудовані функції.
50
50
51
-
For example, `Math.trunc(n)`is a function that "cuts off" the decimal part of a number, e.g`Math.trunc(1.23)`returns`1`.
51
+
Наприклад, функція `Math.trunc(n)`"відрізає" десяткову частину числа, тобто`Math.trunc(1.23)`поверне`1`.
52
52
53
-
In some (very outdated) JavaScript engines, there's no`Math.trunc`, so such code will fail.
53
+
В деяких (дуже старих) рушіях JavaScript, немає функції`Math.trunc`, тому такий код призведе до помилки.
54
54
55
-
As we're talking about new functions, not syntax changes, there's no need to transpile anything here. We just need to declare the missing function.
55
+
Якщо ми говоримо про нові функції, а не синтаксичні вирази, то тут нічого не потрібно транспілювати ("перекладати"). Нам лише потрібно оголосити відсутні функції.
56
56
57
-
A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds missing implementations.
57
+
Скрипт, який оновлює/додає нові функції називається "**поліфіл**" (polyfill). Він "заповнює" прогалини і додає відсутній функціонал.
58
58
59
-
For this particular case, the polyfill for `Math.trunc` is a script that implements it, like this:
59
+
Для нашого випадку з функцією `Math.trunc`, поліфілом буде такий скрипт, який реалізує цю функцію, ось так:
60
60
61
61
```js
62
-
if (!Math.trunc) { //if no such function
63
-
//implement it
62
+
if (!Math.trunc) { //якщо немає такої функції
63
+
//реалізувати її:
64
64
Math.trunc=function(number) {
65
-
// Math.ceil and Math.floor exist even in ancient JavaScript engines
66
-
//they are covered later in the tutorial
65
+
//функції Math.ceil та Math.floor існують навіть в древніх рушіях JavaScript
66
+
//ми розглянемо їх пізніше
67
67
return number <0?Math.ceil(number) :Math.floor(number);
68
68
};
69
69
}
70
70
```
71
71
72
-
JavaScript is a highly dynamic language, scripts may add/modify any functions, even including built-in ones.
72
+
JavaScript дуже динамічна мова -- скрипти можуть додавати чи оновлювати функції, навіть якщо вони вбудовані.
73
73
74
74
Є два цікавих поліфіла:
75
75
- [core js](https://github.com/zloirock/core-js), що підтримує багато функціоналу, дозволяє включати лише необхідні функції.
@@ -78,14 +78,14 @@ JavaScript is a highly dynamic language, scripts may add/modify any functions, e
78
78
79
79
## Підсумки
80
80
81
-
In this chapter we'd like to motivate you to study modern and even "bleeding-edge" language features, even if they aren't yet well-supported by JavaScript engines.
81
+
В цьому розділі ми намагалися вмотивувати вас вивчати сучасний та навіть "передовий" функціонал мови, навіть якщо цей функціонал поки що не підтримується сучасними рушіями JavaScript.
82
82
83
-
Just don't forget to use transpiler (if using modern syntax or operators) and polyfills (to add functions that may be missing). And they'll ensure that the code works.
83
+
Просто не забувайте використовувати транспілятор (якщо будете використовувати сучасний синтаксис чи оператори) та поліфіли (щоб додавати функції, які можуть бути відсутні). Це дозволить впевнитися, що код працює на різних рушіях.
84
84
85
-
For example, later when you're familiar with JavaScript, you can setup a code build system based on [webpack](http://webpack.github.io/) with [babel-loader](https://github.com/babel/babel-loader) plugin.
85
+
Наприклад, пізніше (коли достатньо вивчите JavaScript), ви зможете налаштувати систему складання проєкту на основі [webpack](http://webpack.github.io/) із плаґіном [babel-loader](https://github.com/babel/babel-loader).
86
86
87
-
Good resources that show the current state of support for various features:
88
-
- <https://kangax.github.io/compat-table/es6/> - for pure JavaScript.
89
-
- <https://caniuse.com/> - for browser-related functions.
87
+
Ось хороші ресурси, де можна дізнатися поточний стан підтримки різного функціоналу:
88
+
- <https://kangax.github.io/compat-table/es6/> - для чистого JavaScript.
89
+
- <https://caniuse.com/> - для браузерних функцій.
90
90
91
-
P.S. Google Chrome is usually the most up-to-date with language features, try it if a tutorial demo fails. Most tutorial demos work with any modern browser though.
91
+
P.S. Зазвичай браузер Google Chrome підтримує більшість найновіших функцій мови, спробуйте його, якщо демонстрація не працює. Більшість демонстрацій працюють із сучасними браузерами.
0 commit comments