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: README.ukrainian.md
+50-54Lines changed: 50 additions & 54 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -380,157 +380,153 @@ Read in a different language: [**CN**](./README.chin
380
380
381
381
**В іншому випадку:** Уявіть таку ситуацію – ваша функція очікує числовий аргумент "Знижка", який викликаюча сторона забуває передати, потім ваш код перевіряє, чи Знижка!=0 (розмір дозволеної знижки більший ніж нуль), тоді він дозволить користувачу отримати знижку. О боже, яка неприємна помилка. Бачите її?
382
382
383
-
🔗 [**Читати більше: швидке виявлення помилок**](./sections/errorhandling/failfast.md)
383
+
🔗 [**Читати більше: швидке виявлення помилок**](./sections/errorhandling/failfast.ukrainian.md)
384
384
385
385
<br/><br/>
386
386
387
-
## ![✔] 2.12 Always await promises before returning to avoid a partial stacktrace
387
+
## ![✔] 2.12 Завжди очікуйте проміси перед поверненням, щоб уникнути часткового стеку викликів
388
388
389
-
**TL;DR:** Always do `return await` when returning a promise to benefit full error stacktrace. If a
390
-
function returns a promise, that function must be declared as `async` function and explicitly
391
-
`await` the promise before returning it
389
+
**Коротко:** Завжди використовуйте `return await` при поверненні промісу, щоб отримати повний стек помилок. Якщо функція повертає проміс, ця функція повинна бути оголошена як `async` функція і явно використовувати `await` для промісу перед його поверненням
392
390
393
-
**Otherwise:** The function that returns a promise without awaiting won't appear in the stacktrace.
394
-
Such missing frames would probably complicate the understanding of the flow that leads to the error,
395
-
especially if the cause of the abnormal behavior is inside of the missing function
391
+
**В іншому випадку:** Функція, яка повертає проміс без очікування, не з'явиться у стеку викликів. Такі відсутні кадри, ймовірно, ускладнять розуміння потоку, що призвів до помилки, особливо якщо причина аномальної поведінки знаходиться всередині відсутньої функції
🔗 [**Читати більше: повернення промісу**](./sections/errorhandling/returningpromises.ukrainian.md)
398
394
399
395
<br/><br/><br/>
400
396
401
397
<palign="right"><ahref="#table-of-contents">⬆ Return to top</a></p>
402
398
403
399
# `3. Code Style Practices`
404
400
405
-
## ![✔] 3.1 Use ESLint
401
+
## ![✔] 3.1 Використовуйте ESLint
406
402
407
-
**TL;DR:**[ESLint](https://eslint.org)is the de-facto standard for checking possible code errors and fixing code style, not only to identify nitty-gritty spacing issues but also to detect serious code anti-patterns like developers throwing errors without classification. Though ESLint can automatically fix code styles, other tools like [prettier](https://www.npmjs.com/package/prettier)and[beautify](https://www.npmjs.com/package/js-beautify) are more powerful in formatting the fix and work in conjunction with ESLint
403
+
**Коротко:**[ESLint](https://eslint.org)є фактичним стандартом для перевірки можливих помилок у коді та виправлення стилю коду. Він допомагає не лише виявити дрібні проблеми зі структурою коду, такі як зайві пробіли, але й серйозні антипатерни коду, наприклад, коли розробники кидають помилки без класифікації. Хоча ESLint може автоматично виправляти стиль коду, інші інструменти, такі як [prettier](https://www.npmjs.com/package/prettier)і[beautify](https://www.npmjs.com/package/js-beautify), більш потужні у форматуванні виправлень і працюють разом з ESLint.
408
404
409
-
**Otherwise:**Developers will focus on tedious spacing and line-width concerns and time might be wasted overthinking the project's code style
405
+
**В іншому випадку:**Розробники зосереджуватимуться на нудних питаннях щодо пробілів та ширини рядків, а час може бути витрачено на надмірне обдумування стилю коду проєкту.
410
406
411
-
🔗 [**Read More: Using ESLint and Prettier**](./sections/codestylepractices/eslint_prettier.md)
407
+
🔗 [**Детальніше: Використання ESLint та Prettier**](./sections/codestylepractices/eslint_prettier.ukrainian.md)
412
408
413
409
<br/><br/>
414
410
415
-
## ![✔] 3.2 Node.js specific plugins
411
+
## ![✔] 3.2 Специфічні плагіни для Node.js
416
412
417
-
**TL;DR:**On top of ESLint standard rules that cover vanilla JavaScript, add Node.js specific plugins like [eslint-plugin-node](https://www.npmjs.com/package/eslint-plugin-node), [eslint-plugin-mocha](https://www.npmjs.com/package/eslint-plugin-mocha)and[eslint-plugin-node-security](https://www.npmjs.com/package/eslint-plugin-security)
413
+
**Коротко:**Окрім стандартних правил ESLint, що охоплюють ванільний JavaScript, додайте специфічні плагіни для Node.js, такі як [eslint-plugin-node](https://www.npmjs.com/package/eslint-plugin-node), [eslint-plugin-mocha](https://www.npmjs.com/package/eslint-plugin-mocha)і[eslint-plugin-node-security](https://www.npmjs.com/package/eslint-plugin-security).
418
414
419
-
**Otherwise:**Many faulty Node.js code patterns might escape under the radar. For example, developers might require(variableAsPath) files with a variable given as a path which allows attackers to execute any JS script. Node.js linters can detect such patterns and complain early
415
+
**Інакше:**Багато проблемних шаблонів коду Node.js можуть залишитися непоміченими. Наприклад, розробники можуть використовувати require(variableAsPath) для підключення файлів з передачею змінної як шляху, що дозволяє зловмисникам виконувати будь-який JS-скрипт. Лінтери Node.js можуть виявляти такі шаблони та попереджати про них заздалегідь.
420
416
421
417
<br/><br/>
422
418
423
-
## ![✔] 3.3 Start a Codeblock's Curly Braces on the Same Line
419
+
## ![✔] 3.3 Відкривайте фігурні дужки коду на тому ж рядку
424
420
425
-
**TL;DR:**The opening curly braces of a code block should be on the same line as the opening statement
421
+
**Коротко:**Відкриваючі фігурні дужки блоку коду повинні бути на тому ж рядку, що й оператор відкриття.
426
422
427
-
### Code Example
423
+
### Приклад коду
428
424
429
425
```javascript
430
-
//Do
426
+
//Правильно
431
427
functionsomeFunction() {
432
-
//code block
428
+
//блок коду
433
429
}
434
430
435
-
//Avoid
431
+
//Уникайте
436
432
functionsomeFunction()
437
433
{
438
-
//code block
434
+
//блок коду
439
435
}
440
436
```
441
437
442
-
**Otherwise:**Deferring from this best practice might lead to unexpected results, as seen in the StackOverflow thread below:
438
+
**Інакше:**Відхилення від цієї практики може призвести до несподіваних результатів, як показано в обговоренні на StackOverflow нижче:
443
439
444
-
🔗 [**Read more:** "Why do results vary based on curly brace placement?" (StackOverflow)](https://stackoverflow.com/questions/3641519/why-does-a-results-vary-based-on-curly-brace-placement)
440
+
🔗 [**Читати більше:** "Чому результати варіюються залежно від розміщення фігурних дужок?" (StackOverflow)](https://stackoverflow.com/questions/3641519/why-does-a-results-vary-based-on-curly-brace-placement)
445
441
446
442
<br/><br/>
447
443
448
-
## ![✔] 3.4 Separate your statements properly
444
+
## ![✔] 3.4 Правильно розділяйте свої вирази
449
445
450
-
No matter if you use semicolons or not to separate your statements, knowing the common pitfalls of improper linebreaks or automatic semicolon insertion, will help you to eliminate regular syntax errors.
446
+
Незалежно від того, використовуєте ви крапки з комами для розділення виразів чи ні, знання поширених помилок, пов'язаних з неправильними розривами рядків або автоматичною вставкою крапок з комами, допоможе уникнути регулярних синтаксичних помилок.
451
447
452
-
**TL;DR:**Use ESLint to gain awareness about separation concerns. [Prettier](https://prettier.io/)or[Standardjs](https://standardjs.com/)can automatically resolve these issues.
448
+
**Коротко:**Використовуйте ESLint для підвищення обізнаності про проблеми з розділенням виразів. [Prettier](https://prettier.io/)або[Standardjs](https://standardjs.com/)можуть автоматично вирішити ці проблеми.
453
449
454
-
**Otherwise:**As seen in the previous section, JavaScript's interpreter automatically adds a semicolon at the end of a statement if there isn't one, or considers a statement as not ended where it should, which might lead to some undesired results. You can use assignments and avoid using immediately invoked function expressions to prevent most of the unexpected errors.
450
+
**Інакше:**Як було показано в попередньому розділі, інтерпретатор JavaScript автоматично додає крапку з комою в кінці виразу, якщо її немає, або вважає, що вираз не завершено там, де це потрібно, що може призвести до небажаних результатів. Ви можете використовувати присвоєння і уникати безпосередньо викликаних функціональних виразів (IIFE), щоб уникнути більшості несподіваних помилок.
455
451
456
-
### Code example
452
+
### Приклад коду
457
453
458
454
```javascript
459
-
//Do
455
+
//Правильно
460
456
functiondoThing() {
461
457
// ...
462
458
}
463
459
464
460
doThing()
465
461
466
-
//Do
462
+
//Правильно
467
463
468
464
constitems= [1, 2, 3]
469
465
items.forEach(console.log)
470
466
471
-
//Avoid — throws exception
467
+
//Неправильно — виникає виняток
472
468
constm=newMap()
473
469
consta= [1,2,3]
474
470
[...m.values()].forEach(console.log)
475
471
> [...m.values()].forEach(console.log)
476
472
>^^^
477
473
>SyntaxError: Unexpected token ...
478
474
479
-
//Avoid — throws exception
480
-
constcount=2//it tries to run 2(), but 2 is not a function
475
+
//Неправильно — виникає виняток
476
+
constcount=2//інтерпретатор намагається виконати 2(), але 2 не є функцією
481
477
(functiondoSomething() {
482
-
//do something amazing
478
+
//зробити щось чудове
483
479
}())
484
-
//put a semicolon before the immediate invoked function, after the const definition, save the return value of the anonymous function to a variable or avoid IIFEs altogether
480
+
//вставте крапку з комою перед безпосередньо викликаним виразом, після визначення const, збережіть результат анонімної функції у змінну або уникайте IIFE взагалі
🔗 [**Read more:** "No unexpected multiline ESLint rule"](https://eslint.org/docs/rules/no-unexpected-multiline)
483
+
🔗 [**Читати більше:** "Правило ESLint для крапок з комами"](https://eslint.org/docs/rules/semi)
484
+
🔗 [**Читати більше:** "Правило ESLint для несподіваних розривів рядків"](https://eslint.org/docs/rules/no-unexpected-multiline)
489
485
490
486
<br/><br/>
491
487
492
-
## ![✔] 3.5 Name your functions
488
+
## ![✔] 3.5 Давайте імена своїм функціям
493
489
494
-
**TL;DR:**Name all functions, including closures and callbacks. Avoid anonymous functions. This is especially useful when profiling a node app. Naming all functions will allow you to easily understand what you're looking at when checking a memory snapshot
490
+
**Коротко:**Давайте імена всім функціям, включно із замиканнями та зворотними викликами. Уникайте анонімних функцій. Це особливо корисно при профілюванні Node.js додатків. Присвоєння імен функціям дозволить вам легко розуміти, що ви переглядаєте під час аналізу знімку пам'яті.
495
491
496
-
**Otherwise:**Debugging production issues using a core dump (memory snapshot) might become challenging as you notice significant memory consumption from anonymous functions
492
+
**Інакше:**Виправлення проблем на продакшені за допомогою core dump (знімка пам'яті) може стати складним завданням, оскільки ви можете помітити значне споживання пам'яті анонімними функціями.
497
493
498
494
<br/><br/>
499
495
500
-
## ![✔] 3.6 Use naming conventions for variables, constants, functions and classes
496
+
## ![✔] 3.6 Використовуйте угоди про іменування для змінних, констант, функцій і класів
501
497
502
-
**TL;DR:**Use**_lowerCamelCase_**when naming constants, variables and functions, **_UpperCamelCase_** (capital first letter as well) when naming classes and**_UPPER_SNAKE_CASE_**when naming global or static variables. This will help you to easily distinguish between plain variables, functions, classes that require instantiation and variables declared at global module scope. Use descriptive names, but try to keep them short
498
+
**Коротко:**Використовуйте**_lowerCamelCase_**для називання констант, змінних і функцій, **_UpperCamelCase_** (перша велика літера) для називання класів і**_UPPER_SNAKE_CASE_**для називання глобальних або статичних змінних. Це допоможе легко розрізняти звичайні змінні, функції, класи, які потребують інстанціювання, та змінні, оголошені на рівні глобального модуля. Використовуйте описові імена, але намагайтеся робити їх короткими.
503
499
504
-
**Otherwise:** JavaScript is the only language in the world that allows invoking a constructor ("Class") directly without instantiating it first. Consequently, Classes and function-constructors are differentiated by starting with UpperCamelCase
500
+
**Інакше:** JavaScript — єдина мова у світі, яка дозволяє викликати конструктор ("Клас") напряму без попередньої інстанціювання. Як наслідок, класи та функції-конструктори відрізняються тим, що починаються з UpperCamelCase.
505
501
506
-
### 3.6 Code Example
502
+
### 3.6 Приклад коду
507
503
508
504
```javascript
509
-
//for global variables names we use the const/let keyword and UPPER_SNAKE_CASE
505
+
//для глобальних змінних використовуємо ключові слова const/let і UPPER_SNAKE_CASE
510
506
letMUTABLE_GLOBAL="mutable value"
511
507
constGLOBAL_CONSTANT="immutable value";
512
508
constCONFIG= {
513
509
key:"value",
514
510
};
515
511
516
-
//examples of UPPER_SNAKE_CASE convention in nodejs/javascript ecosystem
517
-
//in javascript Math.PI module
512
+
//приклади угоди UPPER_SNAKE_CASE у екосистемі nodejs/javascript
Якщо ви відформатуєте цей код за допомогою ESLint, він лише видасть попередження про те, що рядок занадто широкий (залежить від налаштувань `max-len`). Prettier автоматично відформатує його для вас.
ESLint та Prettier перетинаються у функції форматування коду, але їх можна легко поєднати за допомогою інших пакетів, таких як [prettier-eslint](https://github.com/prettier/prettier-eslint), [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier) та [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier). Для отримання додаткової інформації про їхні відмінності, ви можете переглянути посилання [тут](https://stackoverflow.com/questions/44690308/whats-the-difference-between-prettier-eslint-eslint-plugin-prettier-and-eslint).
0 commit comments