@karta.io/utils 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # @karta.io/utils
2
+
3
+ Библиотека с общими хелперами, мапперами и плагинами
4
+
5
+ ## Хелперы:
6
+
7
+ - formatMoney
8
+ - createClassName
9
+ - camelizeKeys
10
+ - genLoadingTableRows
11
+ - genRandomNumber
12
+ - getCardNumber
13
+ - getPaginationParams
14
+ - isElementIgnored
15
+ - isEmptyObject
16
+ - unformatNumber
17
+ - validateNumber
18
+
19
+ ## Хуки:
20
+
21
+ - useClassName
package/dist/index.cjs ADDED
@@ -0,0 +1,208 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const camelCase = require('lodash/camelCase');
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
8
+
9
+ const camelCase__default = /*#__PURE__*/_interopDefaultLegacy(camelCase);
10
+
11
+ function viewExample(value) {
12
+ return value;
13
+ }
14
+
15
+ function formatMoney(value, currency, options = { locale: "en-US", minimumFractionDigits: 2, maximumFractionDigits: 2 }) {
16
+ if (Number.isNaN(value) || value === null) {
17
+ return "";
18
+ }
19
+ const formatter = new Intl.NumberFormat(options.locale, {
20
+ minimumFractionDigits: options.minimumFractionDigits,
21
+ maximumFractionDigits: options.maximumFractionDigits,
22
+ ...currency && {
23
+ style: "currency",
24
+ currency
25
+ }
26
+ });
27
+ return formatter.format(value);
28
+ }
29
+
30
+ function createClassName(className) {
31
+ return function f(...classNames) {
32
+ const result = classNames.join("");
33
+ return (...args) => args.length ? f.apply(null, [result, ...args])() : result;
34
+ }(className);
35
+ }
36
+
37
+ function genRandomNumber(min, max) {
38
+ return Math.floor(Math.random() * (max - min + 1)) + min;
39
+ }
40
+
41
+ function getCardNumber(number, options) {
42
+ const { hasOnlyLast4 = false, isHidden = false, dot = "\u2022" } = options || {};
43
+ let result;
44
+ if (isHidden) {
45
+ result = "\u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022";
46
+ } else {
47
+ result = number.replace(/(\d{4})?(\d{4})?(\d{4})?(\d{4})?/, hasOnlyLast4 ? "\u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 $4" : "$1 $2 $3 $4");
48
+ }
49
+ return dot === "\u2022" ? result : result.replaceAll("\u2022", dot);
50
+ }
51
+
52
+ function genLoadingTableRows(columns, limit) {
53
+ const row = columns.reduce((acc, curr) => ({ ...acc, [curr.key]: void 0 }), {});
54
+ return Array.from(Array(limit).keys()).map((item) => ({ id: item, ...row }));
55
+ }
56
+
57
+ function camelizeKeys(object) {
58
+ if (Array.isArray(object)) {
59
+ return object.map((v) => camelizeKeys(v));
60
+ }
61
+ if (object !== null && object.constructor === Object) {
62
+ return Object.keys(object).reduce((result, key) => ({
63
+ ...result,
64
+ [camelCase__default(key)]: camelizeKeys(object[key])
65
+ }), {});
66
+ }
67
+ return object;
68
+ }
69
+
70
+ function validateNumber(value, defaultValue) {
71
+ if (value === "")
72
+ return defaultValue;
73
+ return Number.isNaN(Number(value)) ? defaultValue : Number(value);
74
+ }
75
+
76
+ const LOCALE_RU = "ru-RU";
77
+ const LOCALE_EN = "en-US";
78
+ function unformatNumber(value) {
79
+ if (!value || typeof value !== "string")
80
+ return value;
81
+ const string = value.trim();
82
+ let locale;
83
+ const spaceIndex = string.lastIndexOf(" ");
84
+ const commaIndex = string.lastIndexOf(",");
85
+ const dotIndex = string.lastIndexOf(".");
86
+ const hasSpace = spaceIndex !== -1;
87
+ const hasComma = commaIndex !== -1;
88
+ const hasDot = dotIndex !== -1;
89
+ const commasCount = (string.match(/,/g) || []).length;
90
+ if (!Number.isNaN(Number(string)))
91
+ return Number(string);
92
+ if (hasSpace && hasComma && commaIndex > spaceIndex) {
93
+ locale = LOCALE_RU;
94
+ }
95
+ if (hasSpace && !hasComma && !hasDot) {
96
+ locale = LOCALE_RU;
97
+ }
98
+ if (hasComma && hasDot && dotIndex > commaIndex) {
99
+ locale = LOCALE_EN;
100
+ }
101
+ if (hasComma && !hasSpace && !hasDot && commasCount > 1) {
102
+ locale = LOCALE_EN;
103
+ }
104
+ if (commasCount === 1 && !hasSpace && !hasDot) {
105
+ locale = string.length - 1 - commaIndex === 3 ? LOCALE_EN : LOCALE_RU;
106
+ }
107
+ if (locale === LOCALE_RU) {
108
+ return Number(string.replaceAll(" ", "").replace(",", "."));
109
+ }
110
+ if (locale === LOCALE_EN) {
111
+ return Number(string.replaceAll(",", ""));
112
+ }
113
+ return value;
114
+ }
115
+
116
+ const PAGE_DEFAULT = 1;
117
+ const LIMIT_DEFAULT = 25;
118
+ function getPaginationParams({
119
+ page,
120
+ limit
121
+ }) {
122
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
123
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
124
+ return {
125
+ limit: validatedLimit,
126
+ offset: validatedPage * validatedLimit - validatedLimit
127
+ };
128
+ }
129
+ function getPaginationLimit({
130
+ limit
131
+ }) {
132
+ return validateNumber(limit, LIMIT_DEFAULT);
133
+ }
134
+ function getPaginationOffset({
135
+ page,
136
+ limit
137
+ }) {
138
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
139
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
140
+ return validatedPage * validatedLimit - validatedLimit;
141
+ }
142
+ function getPaginationPages({
143
+ count,
144
+ limit
145
+ }) {
146
+ return Math.ceil(count / validateNumber(limit, LIMIT_DEFAULT));
147
+ }
148
+
149
+ function isElementIgnored({
150
+ ignoredClasses,
151
+ event
152
+ } = {}) {
153
+ if (ignoredClasses && event) {
154
+ return Array.from(event.composedPath()).filter((item) => item.nodeType && item.nodeType !== 9).reduce((acc, item) => {
155
+ const elementClasses = item.getAttribute("class");
156
+ const array = elementClasses ? elementClasses.split(" ") : [];
157
+ return acc.concat(array);
158
+ }, []).some((item) => ignoredClasses.includes(item));
159
+ }
160
+ return false;
161
+ }
162
+
163
+ function isEmptyObject(object) {
164
+ return !object || !Object.keys(object).length;
165
+ }
166
+
167
+ const _bem = (block, blockSuffix, element, modifier) => {
168
+ let cls = block;
169
+ if (blockSuffix) {
170
+ cls += `-${blockSuffix}`;
171
+ }
172
+ if (element) {
173
+ cls += `__${element}`;
174
+ }
175
+ if (modifier) {
176
+ cls += `_${modifier}`;
177
+ }
178
+ return cls;
179
+ };
180
+ const useClassName = (block) => {
181
+ const b = (blockSuffix = "") => _bem(block, blockSuffix, "", "");
182
+ const e = (element) => element ? _bem(block, "", element, "") : "";
183
+ const m = (modifier, condition = true) => modifier && condition ? _bem(block, "", "", modifier) : "";
184
+ const em = (element, modifier, condition = true) => element && modifier && condition ? _bem(block, "", element, modifier) : "";
185
+ return {
186
+ b,
187
+ e,
188
+ m,
189
+ em
190
+ };
191
+ };
192
+
193
+ exports.camelizeKeys = camelizeKeys;
194
+ exports.createClassName = createClassName;
195
+ exports.formatMoney = formatMoney;
196
+ exports.genLoadingTableRows = genLoadingTableRows;
197
+ exports.genRandomNumber = genRandomNumber;
198
+ exports.getCardNumber = getCardNumber;
199
+ exports.getPaginationLimit = getPaginationLimit;
200
+ exports.getPaginationOffset = getPaginationOffset;
201
+ exports.getPaginationPages = getPaginationPages;
202
+ exports.getPaginationParams = getPaginationParams;
203
+ exports.isElementIgnored = isElementIgnored;
204
+ exports.isEmptyObject = isEmptyObject;
205
+ exports.unformatNumber = unformatNumber;
206
+ exports.useClassName = useClassName;
207
+ exports.validateNumber = validateNumber;
208
+ exports.viewExample = viewExample;
@@ -0,0 +1,86 @@
1
+ declare function viewExample(value: string): string;
2
+
3
+ declare function formatMoney(value: number | null, currency?: string, options?: {
4
+ locale: string;
5
+ minimumFractionDigits: number;
6
+ maximumFractionDigits: number;
7
+ }): string;
8
+
9
+ declare function createClassName(className: string): (...classNames: string[]) => string;
10
+
11
+ declare function genRandomNumber(min: number, max: number): number;
12
+
13
+ interface Options {
14
+ hasOnlyLast4: boolean;
15
+ isHidden: boolean;
16
+ dot: string;
17
+ }
18
+ declare function getCardNumber(number: string, options?: Partial<Options>): string;
19
+
20
+ interface Dictionary {
21
+ [keys: string | number]: any;
22
+ }
23
+
24
+ declare function genLoadingTableRows(columns: Dictionary[], limit: number): {
25
+ id: number | undefined;
26
+ key?: undefined;
27
+ }[];
28
+
29
+ declare function camelizeKeys(object: Dictionary): Dictionary;
30
+
31
+ declare function validateNumber(value: string | number, defaultValue: number): number;
32
+
33
+ /**
34
+ * Принимает на вход число в виде строки или числа,
35
+ * возвращает корректное значение типа Number (убирает лишние пробелы и запятые)
36
+ * @example
37
+ * // returns 1000
38
+ * unformatNumber('1 000');
39
+ * @example
40
+ * // returns 1000
41
+ * unformatNumber('1,000')
42
+ * @example
43
+ * // returns 1000.123
44
+ * unformatNummber('1 000,123')
45
+ * @example
46
+ * // returns 1000.123
47
+ * unformatNummber('1,000.123')
48
+ * @param value
49
+ * @return number
50
+ */
51
+ declare function unformatNumber(value: string | number): string | number;
52
+
53
+ declare function getPaginationParams({ page, limit, }: {
54
+ page: string | number;
55
+ limit: string | number;
56
+ }): {
57
+ limit: number;
58
+ offset: number;
59
+ };
60
+ declare function getPaginationLimit({ limit, }: {
61
+ limit: string | number;
62
+ }): number;
63
+ declare function getPaginationOffset({ page, limit, }: {
64
+ page: string | number;
65
+ limit: string | number;
66
+ }): number;
67
+ declare function getPaginationPages({ count, limit, }: {
68
+ count: number;
69
+ limit: string | number;
70
+ }): number;
71
+
72
+ declare function isElementIgnored({ ignoredClasses, event, }?: {
73
+ ignoredClasses?: string[];
74
+ event?: Event;
75
+ }): boolean;
76
+
77
+ declare function isEmptyObject(object: {}): boolean;
78
+
79
+ declare const useClassName: (block: string) => {
80
+ b: (blockSuffix?: string) => string;
81
+ e: (element?: string) => string;
82
+ m: (modifier?: string, condition?: boolean) => string;
83
+ em: (element?: string, modifier?: string, condition?: boolean) => string;
84
+ };
85
+
86
+ export { camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, getCardNumber, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, unformatNumber, useClassName, validateNumber, viewExample };
package/dist/index.mjs ADDED
@@ -0,0 +1,185 @@
1
+ import camelCase from 'lodash/camelCase';
2
+
3
+ function viewExample(value) {
4
+ return value;
5
+ }
6
+
7
+ function formatMoney(value, currency, options = { locale: "en-US", minimumFractionDigits: 2, maximumFractionDigits: 2 }) {
8
+ if (Number.isNaN(value) || value === null) {
9
+ return "";
10
+ }
11
+ const formatter = new Intl.NumberFormat(options.locale, {
12
+ minimumFractionDigits: options.minimumFractionDigits,
13
+ maximumFractionDigits: options.maximumFractionDigits,
14
+ ...currency && {
15
+ style: "currency",
16
+ currency
17
+ }
18
+ });
19
+ return formatter.format(value);
20
+ }
21
+
22
+ function createClassName(className) {
23
+ return function f(...classNames) {
24
+ const result = classNames.join("");
25
+ return (...args) => args.length ? f.apply(null, [result, ...args])() : result;
26
+ }(className);
27
+ }
28
+
29
+ function genRandomNumber(min, max) {
30
+ return Math.floor(Math.random() * (max - min + 1)) + min;
31
+ }
32
+
33
+ function getCardNumber(number, options) {
34
+ const { hasOnlyLast4 = false, isHidden = false, dot = "\u2022" } = options || {};
35
+ let result;
36
+ if (isHidden) {
37
+ result = "\u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022";
38
+ } else {
39
+ result = number.replace(/(\d{4})?(\d{4})?(\d{4})?(\d{4})?/, hasOnlyLast4 ? "\u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 $4" : "$1 $2 $3 $4");
40
+ }
41
+ return dot === "\u2022" ? result : result.replaceAll("\u2022", dot);
42
+ }
43
+
44
+ function genLoadingTableRows(columns, limit) {
45
+ const row = columns.reduce((acc, curr) => ({ ...acc, [curr.key]: void 0 }), {});
46
+ return Array.from(Array(limit).keys()).map((item) => ({ id: item, ...row }));
47
+ }
48
+
49
+ function camelizeKeys(object) {
50
+ if (Array.isArray(object)) {
51
+ return object.map((v) => camelizeKeys(v));
52
+ }
53
+ if (object !== null && object.constructor === Object) {
54
+ return Object.keys(object).reduce((result, key) => ({
55
+ ...result,
56
+ [camelCase(key)]: camelizeKeys(object[key])
57
+ }), {});
58
+ }
59
+ return object;
60
+ }
61
+
62
+ function validateNumber(value, defaultValue) {
63
+ if (value === "")
64
+ return defaultValue;
65
+ return Number.isNaN(Number(value)) ? defaultValue : Number(value);
66
+ }
67
+
68
+ const LOCALE_RU = "ru-RU";
69
+ const LOCALE_EN = "en-US";
70
+ function unformatNumber(value) {
71
+ if (!value || typeof value !== "string")
72
+ return value;
73
+ const string = value.trim();
74
+ let locale;
75
+ const spaceIndex = string.lastIndexOf(" ");
76
+ const commaIndex = string.lastIndexOf(",");
77
+ const dotIndex = string.lastIndexOf(".");
78
+ const hasSpace = spaceIndex !== -1;
79
+ const hasComma = commaIndex !== -1;
80
+ const hasDot = dotIndex !== -1;
81
+ const commasCount = (string.match(/,/g) || []).length;
82
+ if (!Number.isNaN(Number(string)))
83
+ return Number(string);
84
+ if (hasSpace && hasComma && commaIndex > spaceIndex) {
85
+ locale = LOCALE_RU;
86
+ }
87
+ if (hasSpace && !hasComma && !hasDot) {
88
+ locale = LOCALE_RU;
89
+ }
90
+ if (hasComma && hasDot && dotIndex > commaIndex) {
91
+ locale = LOCALE_EN;
92
+ }
93
+ if (hasComma && !hasSpace && !hasDot && commasCount > 1) {
94
+ locale = LOCALE_EN;
95
+ }
96
+ if (commasCount === 1 && !hasSpace && !hasDot) {
97
+ locale = string.length - 1 - commaIndex === 3 ? LOCALE_EN : LOCALE_RU;
98
+ }
99
+ if (locale === LOCALE_RU) {
100
+ return Number(string.replaceAll(" ", "").replace(",", "."));
101
+ }
102
+ if (locale === LOCALE_EN) {
103
+ return Number(string.replaceAll(",", ""));
104
+ }
105
+ return value;
106
+ }
107
+
108
+ const PAGE_DEFAULT = 1;
109
+ const LIMIT_DEFAULT = 25;
110
+ function getPaginationParams({
111
+ page,
112
+ limit
113
+ }) {
114
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
115
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
116
+ return {
117
+ limit: validatedLimit,
118
+ offset: validatedPage * validatedLimit - validatedLimit
119
+ };
120
+ }
121
+ function getPaginationLimit({
122
+ limit
123
+ }) {
124
+ return validateNumber(limit, LIMIT_DEFAULT);
125
+ }
126
+ function getPaginationOffset({
127
+ page,
128
+ limit
129
+ }) {
130
+ const validatedPage = validateNumber(page, PAGE_DEFAULT);
131
+ const validatedLimit = validateNumber(limit, LIMIT_DEFAULT);
132
+ return validatedPage * validatedLimit - validatedLimit;
133
+ }
134
+ function getPaginationPages({
135
+ count,
136
+ limit
137
+ }) {
138
+ return Math.ceil(count / validateNumber(limit, LIMIT_DEFAULT));
139
+ }
140
+
141
+ function isElementIgnored({
142
+ ignoredClasses,
143
+ event
144
+ } = {}) {
145
+ if (ignoredClasses && event) {
146
+ return Array.from(event.composedPath()).filter((item) => item.nodeType && item.nodeType !== 9).reduce((acc, item) => {
147
+ const elementClasses = item.getAttribute("class");
148
+ const array = elementClasses ? elementClasses.split(" ") : [];
149
+ return acc.concat(array);
150
+ }, []).some((item) => ignoredClasses.includes(item));
151
+ }
152
+ return false;
153
+ }
154
+
155
+ function isEmptyObject(object) {
156
+ return !object || !Object.keys(object).length;
157
+ }
158
+
159
+ const _bem = (block, blockSuffix, element, modifier) => {
160
+ let cls = block;
161
+ if (blockSuffix) {
162
+ cls += `-${blockSuffix}`;
163
+ }
164
+ if (element) {
165
+ cls += `__${element}`;
166
+ }
167
+ if (modifier) {
168
+ cls += `_${modifier}`;
169
+ }
170
+ return cls;
171
+ };
172
+ const useClassName = (block) => {
173
+ const b = (blockSuffix = "") => _bem(block, blockSuffix, "", "");
174
+ const e = (element) => element ? _bem(block, "", element, "") : "";
175
+ const m = (modifier, condition = true) => modifier && condition ? _bem(block, "", "", modifier) : "";
176
+ const em = (element, modifier, condition = true) => element && modifier && condition ? _bem(block, "", element, modifier) : "";
177
+ return {
178
+ b,
179
+ e,
180
+ m,
181
+ em
182
+ };
183
+ };
184
+
185
+ export { camelizeKeys, createClassName, formatMoney, genLoadingTableRows, genRandomNumber, getCardNumber, getPaginationLimit, getPaginationOffset, getPaginationPages, getPaginationParams, isElementIgnored, isEmptyObject, unformatNumber, useClassName, validateNumber, viewExample };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@karta.io/utils",
3
+ "version": "0.1.0",
4
+ "description": "karta.io utils for admin and application",
5
+ "author": "Vitaly Blokhin <karambafe@gmail.com>",
6
+ "homepage": "",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "require": "./dist/index.cjs",
11
+ "import": "./dist/index.mjs"
12
+ },
13
+ "./*": "./*"
14
+ },
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.mjs",
17
+ "types": "./dist/index.d.ts",
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "dependencies": {
22
+ "@karta.io/common-data": "^0.1.0",
23
+ "lodash": "4.17.21"
24
+ },
25
+ "devDependencies": {
26
+ "@qvant/prettier-config": "0.1.0",
27
+ "eslint": "8.11.0",
28
+ "eslint-config-airbnb-base": "15.0.0",
29
+ "eslint-plugin-import": "2.25.4",
30
+ "prettier": "2.6.1",
31
+ "typescript": "4.6.2",
32
+ "unbuild": "0.7.0",
33
+ "vitest": "0.7.10"
34
+ },
35
+ "scripts": {
36
+ "dev": "vitest",
37
+ "build": "unbuild",
38
+ "lint": "eslint \"**/*.{ts,js}\" .",
39
+ "lint:fix": "eslint --fix \"**/*.{ts,js}\" .",
40
+ "test": "pnpm lint && vitest run",
41
+ "prettier": "prettier --check --ignore-unknown \"**/*\"",
42
+ "prettier:fix": "prettier --write --ignore-unknown \"**/*\"",
43
+ "prepush": "pnpm run prettier && pnpm run lint",
44
+ "pub": "pnpm build && pnpm publish --no-git-checks"
45
+ },
46
+ "readme": "# @karta.io/utils\n\nБиблиотека с общими хелперами, мапперами и плагинами\n\n## Хелперы:\n\n- formatMoney\n- createClassName\n- camelizeKeys\n- genLoadingTableRows\n- genRandomNumber\n- getCardNumber\n- getPaginationParams\n- isElementIgnored\n- isEmptyObject\n- unformatNumber\n- validateNumber\n\n## Хуки:\n\n- useClassName\n"
47
+ }