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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
const bigintFromNumber = BigInt(10); //same as 10n
const bigintFromNumber = BigInt(10); //те саме що і 10n
```
##Math operators
##Математичні оператори
`BigInt`can mostly be used like a regular number, for example:
`BigInt`можна використовувати як звичайне число, наприклад:
```js run
alert(1n + 2n); // 3
alert(5n / 2n); // 2
```
Please note: the division`5/2`returns the result rounded towards zero, without the decimal part. All operations on bigints return bigints.
Зверніть увагу: поділ`5/2`повертає результат, округлений до нуля, без десяткової частини. Усі операції над великими числами повертають великі числа.
We can't mix bigints and regular numbers:
Ми не можемо змішувати великі та звичайні числа:
```js run
alert(1n + 2); // Error: Cannot mix BigInt and other types
```
We should explicitly convert them if needed: using either`BigInt()`or `Number()`,like this:
Ми повинні явно конвертувати їх, якщо потрібно: використовуючи`BigInt()`або `Number()`,наприклад:
```js run
let bigint = 1n;
let number = 2;
//number to bigint
//число у велике число
alert(bigint + BigInt(number)); // 3
//bigint to number
//велике число у число
alert(Number(bigint) + number); // 3
```
The conversion operations are always silent, never give errors, but if the bigint is too huge and won't fit the number type, then extra bits will be cut off, so we should be careful doing such conversion.
Операції перетворення завжди безшумні, ніколи не дають помилок, але якщо величе число занадто велике і не відповідає типу числа, то зайві біти будуть відрізані, тому ми повинні бути обережними, виконуючи таке перетворення.
````smart header="The unary plus is not supported on bigints"
The unary plus operator`+value`is a well-known way to convert`value`to a number.
````smart header="Унарний плюс не підтримується на великих числах"
Оператор унарний плюс`+value`є добре відомим способом перетворення`value`у число.
In order to avoid confusion, it's not supported on bigints:
Щоб уникнути плутанини, він не підтримується на великих числах:
```js run
let bigint = 1n;
alert( +bigint ); //error
alert( +bigint ); //помилка
```
So we should use `Number()` to convert a bigint to a number.
Тому ми повинні використовувати `Number()`, щоб перетворити велике число в число.
````
##Comparisons
##Порівняння
Comparisons, such as `<`, `>` work with bigints and numbers just fine:
Порівняння, такі як `<`, `>`, чудово працюють з великими та числами:
```js run
alert( 2n > 1n ); // true
alert( 2n > 1 ); // true
```
Please note though, as numbers and bigints belong to different types, they can be equal `==`,but not strictly equal `===`:
Зверніть увагу, оскільки числа та великі числа мають різні типи, вони можуть бути рівними `==`,але не строго рівними `===`:
```js run
alert( 1 == 1n ); // true
alert( 1 === 1n ); // false
```
##Boolean operations
##Булеві операції
When inside`if`or other boolean operations, bigints behave like numbers.
Всередині`if`або інших логічних операцій великі числа поводяться як числа.
For instance, in `if`, bigint`0n`is falsy, other values are truthy:
Наприклад, у `if` величе число`0n`є хибним, інші значення є істинними:
```js run
if (0n) {
//never executes
//ніколи не виконається
}
```
Boolean operators, such as `||`, `&&`and others also work with bigints similar to numbers:
Логічні оператори, такі як `||`, `&&`та інші також працюють з великими числами, подібно до чисел:
```js run
alert( 1n || 2 ); // 1 (1nis considered truthy)
alert( 1n || 2 ); // 1 (1nвважається істинним)
alert( 0n || 2 ); // 2 (0nis considered falsy)
alert( 0n || 2 ); // 2 (0nвважається хибним)
```
##Polyfills
##Поліфіли
Polyfilling bigints is tricky. The reason is that many JavaScript operators, such as `+`, `-`and so on behave differently with bigints compared to regular numbers.
Поліфілення великих чисел є складним. Причина в тому, що багато операторів в JavaScript, таких як `+`, `-`тощо, поводяться по-різному з великими числами порівняно зі звичайними числами.
For example, division of bigints always returns a bigint (rounded if necessary).
Наприклад, поділ великих чисел завжди повертає велике число (за потреби округляється).
To emulate such behavior, a polyfill would need to analyze the code and replace all such operators with its functions. But doing so is cumbersome and would cost a lot of performance.
Щоб емулювати таку поведінку, поліфіл має проаналізувати код і замінити всі такі оператори своїми функціями. Але це громіздко і буде коштувати великої жертви в продуктивності.
So, there's no well-known good polyfill.
Отже, добре відомого хорошого поліфілу не існує.
Although, the other way around is proposed by the developers of[JSBI](https://github.com/GoogleChromeLabs/jsbi)library.
Проте, розробники бібліотеки[JSBI](https://github.com/GoogleChromeLabs/jsbi)пропонують рішення.
This library implements big numbers using its own methods. We can use them instead of native bigints:
Ця бібліотека реалізує підтрику великих чисел, використовуючи власні методи. Ми можемо використовувати їх замість нативних великих чисел:
|Operation |native `BigInt` | JSBI |
|Операція |нативний `BigInt` | JSBI |
|-----------|-----------------|------|
|Creation from Number | `a = BigInt(789)` | `a = JSBI.BigInt(789)` |
...And then use the polyfill (Babel plugin) to convertJSBIcalls to native bigints for those browsers that support them.
...А потім скористайтеся поліфілом (плагін для Babel), щоб перетворити викликиJSBIна нативні великі числа для тих браузерів, які їх підтримують.
In other words, this approach suggests that we write code in JSBIinstead of native bigints. But JSBIworks with numbers as with bigints internally, emulates them closely following the specification, so the code will be "bigint-ready".
Іншими словами, цей підхід припускає, що ми пишемо код на JSBIзамість нативних великих чисел. Але JSBIвсередині працює з числами як із великими числами, емулює їх відповідно до специфікації, тож код буде «готовий до великих чисел».
We can use suchJSBIcode "as is" for engines that don't support bigints and for those that do support - the polyfill will convert the calls to native bigints.
Ми можемо використовувати такий кодJSBI«як є» для двигунців, які не підтримують великі числа, а для тих, які підтримують - поліфіл конвертуватиме виклики в нативні великі числа.
##References
##Посилання
- [MDNdocs on BigInt](mdn:/JavaScript/Reference/Global_Objects/BigInt).
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.