|
@@ -1,23 +1,21 @@
|
|
|
## @e22m4u/js-format
|
|
## @e22m4u/js-format
|
|
|
|
|
|
|
|
-*English | [Русский](README-ru.md)*
|
|
|
|
|
|
|
+Утилита интерполяции строк для JavaScript.
|
|
|
|
|
|
|
|
-The string interpolation utility for JavaScript.
|
|
|
|
|
|
|
+- стандартные спецификаторы `%s`, `%d` и `%j` (см. [`util.format`](https://nodejs.org/api/util.html#utilformatformat-args))
|
|
|
|
|
+- `%v` вывод примитивного значения или имени конструктора
|
|
|
|
|
+- `%l` вывод элементов массива через запятую `"foo", 10, true`
|
|
|
|
|
|
|
|
-- standard specifiers `%s`, `%d`, and `%j` (see [`util.format`](https://nodejs.org/api/util.html#utilformatformat-args))
|
|
|
|
|
-- `%v` outputs primitive value or constructor name
|
|
|
|
|
-- `%l` outputs an array as a comma-separated list `"foo", 10, true`
|
|
|
|
|
|
|
+Дополнительно:
|
|
|
|
|
+- встроенный класс `Errorf` с интерполяцией сообщения об ошибке
|
|
|
|
|
|
|
|
-Additionally:
|
|
|
|
|
-- built-in `Errorf` class with error message interpolation
|
|
|
|
|
|
|
+## Мотивация
|
|
|
|
|
|
|
|
-## Motivation
|
|
|
|
|
-
|
|
|
|
|
-Аn error message may need to interpolate certain values
|
|
|
|
|
-in the message string. In this case, a problem is accurately
|
|
|
|
|
-determine the type of the output value, because the standard
|
|
|
|
|
-specifier `%s` treats strings, numbers, and other types
|
|
|
|
|
-in the same way.
|
|
|
|
|
|
|
+При выводе сообщения об ошибке может возникнуть потребность
|
|
|
|
|
+включения некоторых значений в строку сообщения. В этом случае
|
|
|
|
|
+возникает проблема, когда невозможно точно определить тип
|
|
|
|
|
+выводимого значения, так как стандартный спецификатор `%s`
|
|
|
|
|
+одинаково обрабатывает строки, числа и другие типы.
|
|
|
|
|
|
|
|
```js
|
|
```js
|
|
|
import {format} from 'util';
|
|
import {format} from 'util';
|
|
@@ -28,8 +26,8 @@ console.log(format(`A boolean required, but %s given.`, '8'));
|
|
|
// > A boolean required, but 8 given.
|
|
// > A boolean required, but 8 given.
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-In the example above, the string `'8'` and the number `8`
|
|
|
|
|
-are output identically. A similar problem occurs with objects.
|
|
|
|
|
|
|
+В примере выше строка `'8'` и число `8` выводятся одинаково.
|
|
|
|
|
+Похожая проблема возникает при выводе объектов.
|
|
|
|
|
|
|
|
```js
|
|
```js
|
|
|
import {format} from 'util';
|
|
import {format} from 'util';
|
|
@@ -40,13 +38,13 @@ console.log(format(`A boolean required, but %s given.`, 'Oct 18 2024 13:04:30'))
|
|
|
// > A boolean required, but Oct 18 2024 13:04:30 given.
|
|
// > A boolean required, but Oct 18 2024 13:04:30 given.
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-The module extends standard specifiers with additional
|
|
|
|
|
-`%v` and `%l`, which wrap strings in quotes and output
|
|
|
|
|
-a constructor name for objects.
|
|
|
|
|
|
|
+Данный модуль расширяет стандартные спецификаторы дополнительным
|
|
|
|
|
+`%v` и `%l`, которые оборачивают строки в кавычки, а для объектов
|
|
|
|
|
+выводят имя конструктора.
|
|
|
|
|
|
|
|
```js
|
|
```js
|
|
|
// import {format} from 'util';
|
|
// import {format} from 'util';
|
|
|
-import {format} from '@e22m4u/js-format'; // replace "util" package
|
|
|
|
|
|
|
+import {format} from '@e22m4u/js-format'; // заменяем пакет "util"
|
|
|
|
|
|
|
|
console.log(format(`A boolean required, but %v given.`, 8));
|
|
console.log(format(`A boolean required, but %v given.`, 8));
|
|
|
console.log(format(`A boolean required, but %v given.`, '8'));
|
|
console.log(format(`A boolean required, but %v given.`, '8'));
|
|
@@ -59,16 +57,16 @@ console.log(format(`A boolean required, but %v given.`, 'Oct 18 2024 13:04:30'))
|
|
|
// > A boolean required, but "Oct 18 2024 13:04:30" given.
|
|
// > A boolean required, but "Oct 18 2024 13:04:30" given.
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-For more details about the new specifiers,
|
|
|
|
|
-see the [Specifiers](#Specifiers) section.
|
|
|
|
|
|
|
+Подробнее о новых спецификаторах см. в разделе
|
|
|
|
|
+[Спецификаторы](#Спецификаторы).
|
|
|
|
|
|
|
|
-## Installation
|
|
|
|
|
|
|
+## Установка
|
|
|
|
|
|
|
|
```bash
|
|
```bash
|
|
|
npm install @e22m4u/js-format
|
|
npm install @e22m4u/js-format
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-The module supports ESM and CommonJS standards.
|
|
|
|
|
|
|
+Модуль поддерживает ESM и CommonJS стандарты.
|
|
|
|
|
|
|
|
*ESM*
|
|
*ESM*
|
|
|
|
|
|
|
@@ -82,27 +80,26 @@ import {format} from '@e22m4u/js-format';
|
|
|
const {format} = require('@e22m4u/js-format');
|
|
const {format} = require('@e22m4u/js-format');
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-## Specifiers
|
|
|
|
|
|
|
+## Спецификаторы
|
|
|
|
|
|
|
|
-The `format` method returns a formatted string using
|
|
|
|
|
-the first argument as a printf-like template which can
|
|
|
|
|
-contain zero or more format specifiers. Each specifier
|
|
|
|
|
-is replaced with the converted value from the corresponding
|
|
|
|
|
-argument.
|
|
|
|
|
|
|
+Метод `format` возвращает отформатированную строку, используя
|
|
|
|
|
+первый аргумент как *printf*-подобный шаблон, который может
|
|
|
|
|
+содержать ноль или более спецификаторов. Каждый спецификатор
|
|
|
|
|
+заменяется преобразованным значением из соответствующего
|
|
|
|
|
+аргумента.
|
|
|
|
|
|
|
|
-| specifier | description |
|
|
|
|
|
-|-----------|------------------------------------------|
|
|
|
|
|
-| `%s` | `String` will be used to convert a value |
|
|
|
|
|
-| `%d` | `Number` will be used to convert a value |
|
|
|
|
|
-| `%j` | JSON representation |
|
|
|
|
|
-| `%v` | see below |
|
|
|
|
|
-| `%l` | see below |
|
|
|
|
|
|
|
+| specifier | description |
|
|
|
|
|
+|-----------|----------------------------------------------|
|
|
|
|
|
+| `%s` | использует `String` для конвертации значения |
|
|
|
|
|
+| `%d` | использует `Number` для конвертации значения |
|
|
|
|
|
+| `%j` | представление значения в виде JSON |
|
|
|
|
|
+| `%v` | см. ниже |
|
|
|
|
|
+| `%l` | см. ниже |
|
|
|
|
|
|
|
|
### %v
|
|
### %v
|
|
|
|
|
|
|
|
-Strings are wrapped in quotes, other primitives are converted
|
|
|
|
|
-to strings, and for more complex types the constructor name
|
|
|
|
|
-is output.
|
|
|
|
|
|
|
+Строки оборачиваются в кавычки, остальные примитивы приводятся
|
|
|
|
|
+к строке, а для более сложных типов выводится имя конструктора.
|
|
|
|
|
|
|
|
```js
|
|
```js
|
|
|
format('It is %v', 'foo'); // It is "foo"
|
|
format('It is %v', 'foo'); // It is "foo"
|
|
@@ -121,11 +118,11 @@ format('It is %v', undefined); // It is undefined
|
|
|
format('It is %v', null); // It is null
|
|
format('It is %v', null); // It is null
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-The `%v` specifier was designed to output values in error messages
|
|
|
|
|
-when it's important to have an idea of their types. However, outputting
|
|
|
|
|
-the contents of an object may be excessive for such a task. For this reason,
|
|
|
|
|
-objects are converted to the constructor name, which allows for a relatively
|
|
|
|
|
-accurate determination of the output value's type.
|
|
|
|
|
|
|
+Спецификатор `%v` проектировался для вывода значений в сообщениях
|
|
|
|
|
+об ошибке, когда важно иметь представление об их типах. При этом,
|
|
|
|
|
+вывод содержимого объекта может быть избыточен для такой задачи.
|
|
|
|
|
+По этой причине, объекты приводятся к имени конструктора, что
|
|
|
|
|
+позволяет относительно точно определить тип выводимого значения.
|
|
|
|
|
|
|
|
```js
|
|
```js
|
|
|
class MyClass {}
|
|
class MyClass {}
|
|
@@ -137,22 +134,22 @@ format('It is %v', new MyClass()); // It is MyClass (instance)
|
|
|
|
|
|
|
|
### %l
|
|
### %l
|
|
|
|
|
|
|
|
-Outputs array elements separated by commas.
|
|
|
|
|
|
|
+Вывод элементов массива через запятую.
|
|
|
|
|
|
|
|
```js
|
|
```js
|
|
|
format('An array of %l', ['foo', 10, true]);
|
|
format('An array of %l', ['foo', 10, true]);
|
|
|
// An array of "foo", 10, true
|
|
// An array of "foo", 10, true
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-Array elements are converted to strings following
|
|
|
|
|
-the logic of the `%v` specifier.
|
|
|
|
|
|
|
+Элементы массива приводятся к строке по логике
|
|
|
|
|
+спецификатора `%v`
|
|
|
|
|
|
|
|
## `Errorf`
|
|
## `Errorf`
|
|
|
|
|
|
|
|
-The `Errorf` class constructor passes its arguments
|
|
|
|
|
-to the `format` function to form an error message.
|
|
|
|
|
|
|
+Конструктор класса `Errorf` передает свои аргументы
|
|
|
|
|
+функции `format` для формирования сообщения об ошибке.
|
|
|
|
|
|
|
|
-Example:
|
|
|
|
|
|
|
+Пример:
|
|
|
|
|
|
|
|
```js
|
|
```js
|
|
|
import {Errorf} from '@e22m4u/js-format';
|
|
import {Errorf} from '@e22m4u/js-format';
|
|
@@ -165,12 +162,12 @@ throw new Errorf(
|
|
|
// Error: It requires one of true, false, "y", "n", but Map given.
|
|
// Error: It requires one of true, false, "y", "n", but Map given.
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-## Tests
|
|
|
|
|
|
|
+## Тесты
|
|
|
|
|
|
|
|
```bash
|
|
```bash
|
|
|
npm run test
|
|
npm run test
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
-## License
|
|
|
|
|
|
|
+## Лицензия
|
|
|
|
|
|
|
|
MIT
|
|
MIT
|