@alfalab/utils
Advanced tools
Comparing version 1.16.0 to 1.17.0-next.2
@@ -1,620 +0,19 @@ | ||
import { currency, countries } from '@alfalab/data'; | ||
import isPlainObject from 'lodash/isPlainObject'; | ||
import transform from 'lodash/transform'; | ||
/** | ||
* Возвращает последние цифры номера счёта в формате `··XXXX` | ||
* @param accountNumber - Номер счёта. | ||
* @param additionalParams - Дополнительные параметры. | ||
* @param additionalParams.countOfResultDigits - Количество оставшихся цифр. По умолчанию 4. | ||
*/ | ||
function cropAccountNumber(accountNumber, _a) { | ||
var _b = _a === void 0 ? {} : _a, _c = _b.countOfResultDigits, countOfResultDigits = _c === void 0 ? 4 : _c; | ||
if (!accountNumber) { | ||
return accountNumber; | ||
} | ||
return "\u00B7\u00B7" + accountNumber.slice(-countOfResultDigits); | ||
} | ||
var ACCOUNT_SPLIT_REGEX = /^(\d{5})(\d{3})(\d)(\d{4})(\d{7})$/; | ||
var ACCOUNT_FORMAT = '$1 $2 $3 $4 $5'; | ||
/** | ||
* Возвращает отформатированное значение счёта. | ||
* Разделяет пробелами число на группы. | ||
* XXXXX XXX X XXXX XXXXXXX | ||
* | ||
* @param value Номер счёта. | ||
*/ | ||
function formatAccount(value) { | ||
if (!value) { | ||
return ''; | ||
} | ||
return value.replace(ACCOUNT_SPLIT_REGEX, ACCOUNT_FORMAT); | ||
} | ||
/** | ||
* Возвращает знак валюты по ISO коду. | ||
* | ||
* @param currencyCode Код валюты. | ||
*/ | ||
var getCurrencySymbol = function (currencyCode) { | ||
return currency.CURRENCY_SYMBOLS[currencyCode]; | ||
}; | ||
/** | ||
* Дробит мажорную часть суммы на части по указанному символу. | ||
* | ||
* @param amount Сумма для разбивки на части | ||
* @param partSize Размер частей суммы | ||
* @param splitter Символ, разбивающий части суммы | ||
* @param splitFrom Длина суммы, начиная с которой необходимо осуществлять разбивку. По-умолчанию длина | ||
* равняется пяти по требованию гайдлайнов: https://design.alfabank.ru/patterns/amount. Пример: 2900 - не разбивается, | ||
* 29 000 - разбивается. | ||
*/ | ||
var splitAmount = function (amount, partSize, splitter, splitFrom) { | ||
if (partSize === void 0) { partSize = 3; } | ||
if (splitFrom === void 0) { splitFrom = 5; } | ||
var splittingRegExp = "\\B(?=(\\d{" + partSize + "})+(?!\\d))"; | ||
// Если длина суммы меньше требуемой, не форматируем сумму | ||
if (amount.length < splitFrom) { | ||
return amount; | ||
} | ||
return amount.replace(new RegExp(splittingRegExp, 'g'), splitter); | ||
}; | ||
var AMOUNT_MAJOR_PART_SIZE = 3; | ||
var AMOUNT_SPLIT_CODE_FROM = 4; | ||
// Reference: https://jkorpela.fi/dashes.html | ||
var NEGATIVE_SYMBOLS = { | ||
/** Unicode: U+2212. An arithmetic operator */ | ||
'minus-sign': '−', | ||
/** Unicode: U+002D. The Ascii hyphen. Used in inputs */ | ||
'hyphen-minus': '-', | ||
}; | ||
var THINSP = String.fromCharCode(8201); //   | ||
var MMSP = String.fromCharCode(8287); // средний математический пробел | ||
var AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR = ','; | ||
/** | ||
* Возвращает код для валюты взависимости от формата | ||
*/ | ||
var getCurrencyCodeWithFormat = function (currency, codeFormat) { | ||
if (!currency) { | ||
return ''; | ||
} | ||
return codeFormat === 'symbolic' | ||
? getCurrencySymbol(currency) | ||
: currency; | ||
}; | ||
/** | ||
* Возвращает разделитель для кода валюты взависимости от формата | ||
*/ | ||
var getCurrencySeparator = function (codeFormat) { return (codeFormat === 'symbolic' ? THINSP : MMSP); }; | ||
/** | ||
* Форматирует значение вместе с кодом валюты | ||
*/ | ||
var formatWithCurrency = function (value, currencyCode, separator) { return [value, currencyCode].filter(Boolean).join(separator); }; | ||
/** | ||
* Форматирует значение суммы | ||
* согласно гайдлайну https://design.alfabank.ru/patterns/amount | ||
*/ | ||
var formatAmount = function (_a) { | ||
var value = _a.value, currency = _a.currency, minority = _a.minority, view = _a.view, _b = _a.negativeSymbol, negativeSymbol = _b === void 0 ? 'minus-sign' : _b, _c = _a.codeFormat, codeFormat = _c === void 0 ? 'symbolic' : _c; | ||
var currencySymbol = getCurrencyCodeWithFormat(currency, codeFormat); | ||
var currencySeparator = getCurrencySeparator(codeFormat); | ||
if (value === null) { | ||
return { | ||
majorPart: '', | ||
minorPart: '', | ||
formatted: '', | ||
currencySymbol: currencySymbol, | ||
currencySeparator: currencySeparator, | ||
formattedWithCurrency: formatWithCurrency(value, currencySymbol, currencySeparator), | ||
}; | ||
} | ||
// eslint-disable-next-line no-param-reassign | ||
minority = minority === 0 ? 1 : minority; // because Math.log(0) => -Infinity | ||
var fractionDigits = Math.log(minority) * Math.LOG10E; | ||
var valueAbsStr = (Math.abs(value) / minority).toFixed(fractionDigits); | ||
var majorPart = valueAbsStr.split('.')[0]; | ||
var _d = valueAbsStr.split('.'), minorPart = _d[1]; | ||
if (view === 'default' && value % minority === 0) { | ||
minorPart = ''; | ||
} | ||
var majorPartSplitted = splitAmount(majorPart, AMOUNT_MAJOR_PART_SIZE, MMSP, AMOUNT_SPLIT_CODE_FROM); | ||
var majorPartFormatted = value < 0 ? NEGATIVE_SYMBOLS[negativeSymbol] + majorPartSplitted : majorPartSplitted; | ||
var formattedValueStr = minorPart | ||
? majorPartFormatted + AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR + minorPart | ||
: majorPartFormatted; | ||
return { | ||
majorPart: majorPartFormatted, | ||
minorPart: minorPart, | ||
currencySymbol: currencySymbol, | ||
formatted: formattedValueStr, | ||
currencySeparator: currencySeparator, | ||
formattedWithCurrency: formatWithCurrency(formattedValueStr, currencySymbol, currencySeparator), | ||
}; | ||
}; | ||
var Locale; | ||
(function (Locale) { | ||
Locale["RU"] = "ru"; | ||
Locale["EN"] = "en"; | ||
})(Locale || (Locale = {})); | ||
var _a; | ||
var UNITS_COUNT = 4; | ||
var SIZE_UNITS = (_a = {}, | ||
_a[Locale.RU] = ['Б', 'КБ', 'МБ', 'ГБ'], | ||
_a[Locale.EN] = ['B', 'KB', 'MB', 'GB'], | ||
_a); | ||
var humanizeNumberPartOfFileSize = function (value, factor) { | ||
var maxFactor = UNITS_COUNT - 1; | ||
if (value > 99 && factor === maxFactor) | ||
return '99+'; | ||
return "" + Number(value.toFixed(2)); | ||
}; | ||
var parseFileSize = function (fileSize) { | ||
var parsedFileSize = Number(fileSize); | ||
if (Number.isNaN(parsedFileSize)) | ||
return 0; | ||
return parsedFileSize; | ||
}; | ||
/** | ||
* Возвращает отформатированное значение размера файла. | ||
* Разделяет пробелом число и единицу измерения. | ||
* | ||
* Примеры: | ||
* 976.56 KB, | ||
* 1000 B, | ||
* 93.13 GB, | ||
* 99+ GB - Если файл превышает 99 GB, | ||
* 0 B - Если приходит строка, которую невозможно привести к числу | ||
*/ | ||
var formatFileSize = function (fileSize, locale) { | ||
if (locale === void 0) { locale = Locale.EN; } | ||
var maxFactor = UNITS_COUNT - 1; | ||
var humanSize = parseFileSize(fileSize); | ||
var factor = 0; | ||
while (humanSize >= 1024 && factor < maxFactor) { | ||
humanSize /= 1024; | ||
factor += 1; | ||
} | ||
return humanizeNumberPartOfFileSize(humanSize, factor) + " " + SIZE_UNITS[locale][factor]; | ||
}; | ||
/** | ||
* Удаляет форматирование номера телефона | ||
* @param phone Отформатированный номер телефона с кодом страны | ||
* @returns Номер телефона в формате 71112223344/88002223344 | ||
*/ | ||
var getRawPhoneNumber = function (phone) { return phone.replace(/\D+/g, ''); }; | ||
/** | ||
* Форматирует номер телефона | ||
* @param phone Номер телефона в любом формате с кодом страны | ||
* @returns Номер телефона в формате +7 111 222-33-44/8 800 222-33-44 | ||
*/ | ||
var formatPhoneNumber = function (phone) { | ||
var rawPhone = getRawPhoneNumber(phone); | ||
var formattedPhone = rawPhone.replace(/(\d)(\d{3})(\d{3})(\d{2})(\d{2})/, "$1 $2 $3-$4-$5"); | ||
return formattedPhone[0] === '7' ? '+'.concat(formattedPhone) : formattedPhone; | ||
}; | ||
/** | ||
* Маскирует номер телефона. | ||
* Номер должен быть уже отформатирован. | ||
* TODO: сделать, чтобы number можно было принимать любой (отформатированный/неотформатированный) | ||
* | ||
* @param {String} number Отформатированный номер телефона | ||
* @returns {String} | ||
*/ | ||
function maskPhoneNumber(number) { | ||
var first = number.substr(0, 2); | ||
var last = number.substr(number.length - 5, number.length); | ||
return first + " \u00B7\u00B7\u00B7 \u00B7\u00B7\u00B7 " + last; | ||
} | ||
var phoneNumber = { | ||
format: formatPhoneNumber, | ||
getRaw: getRawPhoneNumber, | ||
mask: maskPhoneNumber, | ||
}; | ||
function getAllCurrencyCodes() { | ||
return Object.keys(currency.CURRENCY_SYMBOLS); | ||
} | ||
var formatCountry = function (_a) { | ||
_a[0]; var name = _a[1], iso2 = _a[2], dialCode = _a[3], priority = _a[4], areaCodes = _a[5]; | ||
return ({ | ||
name: name, | ||
iso2: iso2, | ||
dialCode: dialCode, | ||
priority: priority, | ||
areaCodes: areaCodes !== null && areaCodes !== void 0 ? areaCodes : null, | ||
}); | ||
}; | ||
var getCountries = function () { | ||
return countries.map(formatCountry).sort(function (a, b) { return a.name.localeCompare(b.name); }); | ||
}; | ||
var getCountriesHash = function () { | ||
return countries.reduce(function (acc, country) { | ||
var iso2 = country[2]; | ||
acc[iso2] = formatCountry(country); | ||
return acc; | ||
}, {}); | ||
}; | ||
/** | ||
* Возвращает `true`, если элемент переполнен | ||
* @param element HTML-элемент | ||
*/ | ||
function isOverflown(element) { | ||
return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth; | ||
} | ||
/** | ||
* Возвращает слово в необходимой форме, зависимой от значения `count`. | ||
* | ||
* @example | ||
* pluralize(1, 'день', 'дня', 'дней'); // день | ||
* pluralize(2, 'день', 'дня', 'дней'); // дня | ||
* pluralize(5, 'день', 'дня', 'дней'); // дней | ||
* | ||
* @param {number} count - Число. | ||
* @param {string} nominative - Слово в именительном падеже единственного числа | ||
* @param {string} genitive - Слово в родительном падеже единственного числа | ||
* @param {string} plural - Слово во множественном числе | ||
* | ||
* @returns {string} | ||
*/ | ||
var pluralize = function (count, nominative, genitive, plural) { | ||
var normalizedNumber = count % 100; | ||
if (normalizedNumber >= 11 && normalizedNumber <= 19) { | ||
return plural; | ||
} | ||
var remainder = normalizedNumber % 10; | ||
switch (remainder) { | ||
case 1: | ||
return nominative; | ||
case 2: | ||
case 3: | ||
case 4: | ||
return genitive; | ||
default: | ||
return plural; | ||
} | ||
}; | ||
/** | ||
* Приводит секунды к формату `hh:mm:ss` и возвращает объект с ними. | ||
*/ | ||
function secondsToTime(seconds) { | ||
var h = Math.floor(seconds / 60 / 60); | ||
var m = Math.floor(seconds / 60) % 60; | ||
var s = seconds - h * 3600 - m * 60; | ||
return { | ||
hours: "" + numPad('00', h), | ||
minutes: "" + numPad('00', m), | ||
seconds: "" + numPad('00', s), | ||
}; | ||
} | ||
function numPad(pad, num) { | ||
return typeof num === 'undefined' ? pad : (pad + num).slice(-pad.length); | ||
} | ||
/** | ||
* Возвращает true/false при проверке номера валидности карты по алгоритму Луна | ||
*/ | ||
var isValidCardNumber = function (setValue) { | ||
var ch = 0; | ||
var num = setValue.replace(/\D/g, ''); | ||
if (num === '') | ||
return false; | ||
for (var i = 0; i < num.length; i++) { | ||
var n = parseInt(num[i], 10); | ||
ch += 0 === i % 2 && (n *= 2) > 9 ? n - 9 : n; | ||
} | ||
return ch % 10 === 0; | ||
}; | ||
var EMAIL_PARTS_SEPARATOR = '@'; | ||
var DOMAIN_PARTS_SEPARATOR = '.'; | ||
var MAX_ACCOUNT_LENGTH = 64; | ||
var MAX_ADDRES_LENGTH = 255; | ||
var MAX_DOMAIN_LENGTH = 63; | ||
var EMAIL_REGEX = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/; | ||
/** | ||
* Возвращает true для валидного email, иначе false | ||
* | ||
* @param email Строка содержащая email | ||
*/ | ||
function isValidEmail(email) { | ||
if (!email) | ||
return false; | ||
var emailParts = email.split(EMAIL_PARTS_SEPARATOR); | ||
if (emailParts.length !== 2) | ||
return false; | ||
var account = emailParts[0], address = emailParts[1]; | ||
var accountTooLong = account.length > MAX_ACCOUNT_LENGTH; | ||
var addressTooLong = address.length > MAX_ADDRES_LENGTH; | ||
if (accountTooLong || addressTooLong) | ||
return false; | ||
var domainParts = address.split(DOMAIN_PARTS_SEPARATOR); | ||
var domainTooLong = domainParts.some(function (part) { return part.length > MAX_DOMAIN_LENGTH; }); | ||
if (domainTooLong) | ||
return false; | ||
return EMAIL_REGEX.test(email); | ||
} | ||
// prettier-ignore | ||
var keyboardsLayouts = { | ||
en: [ | ||
// нижний регистр | ||
/* mac */ '§', /* win */ '`', | ||
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', | ||
'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '\\', | ||
'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', | ||
// нижний регистр через shift | ||
/* mac */ '±', /* win */ '~', | ||
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', | ||
'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', '|', | ||
'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', | ||
'@', | ||
], | ||
ru: [ | ||
// нижний регистр | ||
'ё', 'ё', | ||
'й', 'ц', 'у', 'к', 'е', 'н', 'г', 'ш', 'щ', 'з', 'х', 'ъ', | ||
'ф', 'ы', 'в', 'а', 'п', 'р', 'о', 'л', 'д', 'ж', 'э', 'ё', | ||
'я', 'ч', 'с', 'м', 'и', 'т', 'ь', 'б', 'ю', '/', | ||
// нижний регистр через shift | ||
'Ё', 'Ё', | ||
'Й', 'Ц', 'У', 'К', 'Е', 'Н', 'Г', 'Ш', 'Щ', 'З', 'Х', 'Ъ', | ||
'Ф', 'Ы', 'В', 'А', 'П', 'Р', 'О', 'Л', 'Д', 'Ж', 'Э', 'Ё', | ||
'Я', 'Ч', 'С', 'М', 'И', 'Т', 'Ь', 'Б', 'Ю', '?', | ||
'"', | ||
], | ||
}; | ||
/** regex для раскладок клавиатуры */ | ||
var keyboardLanguages = { | ||
en: /[a-z[\]{};:'"\\|,.<>?§±`~]/i, | ||
ru: /[а-яё"/?]/i, | ||
}; | ||
/** | ||
* Проверяет строку на совпадение с раскладкой клавиатуры. | ||
*/ | ||
function isKeyboardLayout(string, keyboardAlias) { | ||
if (!string.length) | ||
return false; | ||
// your keyboard | ||
var keyboardLanguage = keyboardLanguages[keyboardAlias]; | ||
// недопустимая раскладка клавиатуры | ||
if (!keyboardLanguage) | ||
return false; | ||
var index = 0; | ||
var isValid = false; | ||
while (index < string.length) { | ||
var letter = string[index]; | ||
if (keyboardLanguage.test(letter)) { | ||
isValid = true; | ||
return true; | ||
} | ||
index += 1; | ||
} | ||
return isValid; | ||
} | ||
/** | ||
* Конвертирует символы из одной раскладки в другую. | ||
*/ | ||
function keyboardSwitcher(characters, from, to) { | ||
if (characters === void 0) { characters = ''; } | ||
if (from === void 0) { from = 'en'; } | ||
if (to === void 0) { to = 'ru'; } | ||
// incoming text string | ||
var textToConvert = characters; | ||
// if characters is empty stop working | ||
if (!textToConvert || !textToConvert.length) | ||
return ''; | ||
// if incoming text and current keyboard not equal | ||
if (!isKeyboardLayout(textToConvert, from)) { | ||
return characters; | ||
} | ||
// current keyboard layout | ||
var locale = keyboardsLayouts[from]; | ||
// convert characters to this keyboard layout | ||
var localeOn = keyboardsLayouts[to]; | ||
var convertedText = ''; | ||
var index = 0; | ||
while (index < textToConvert.length) { | ||
var letter = textToConvert[index]; | ||
var letterIndex = locale.indexOf(letter); | ||
convertedText += localeOn[letterIndex]; | ||
index += 1; | ||
} | ||
return convertedText; | ||
} | ||
function switchToKeyboard(characters, keyboardAlias) { | ||
var textToConvert = characters; | ||
if (!textToConvert.length) | ||
return ''; | ||
var keyboards = Object.keys(keyboardLanguages); | ||
var index = 0; | ||
var convertedText = ''; | ||
var _loop_1 = function () { | ||
var letter = textToConvert[index]; | ||
var locale = ''; | ||
keyboards.map(function (keyboardKey) { | ||
var isKeyboardIncludesLetter = isKeyboardLayout(letter, keyboardKey); | ||
if (isKeyboardIncludesLetter && keyboardKey !== keyboardAlias) { | ||
locale = keyboardKey; | ||
return ''; | ||
} | ||
return ''; | ||
}); | ||
var returnedLetter = locale === keyboardAlias ? letter : keyboardSwitcher(letter, locale, keyboardAlias); | ||
convertedText += returnedLetter; | ||
index += 1; | ||
}; | ||
while (index < textToConvert.length) { | ||
_loop_1(); | ||
} | ||
return convertedText; | ||
} | ||
/** | ||
* Автоматически переводит английскую раскладку на русскую при вводе пользователем. | ||
*/ | ||
var formatToRussian = function (value, isCapitalize) { | ||
if (value === void 0) { value = ''; } | ||
if (isCapitalize === void 0) { isCapitalize = false; } | ||
if (!value) | ||
return ''; | ||
// check user keyboard and if it need convert to russian | ||
var enteredValue = switchToKeyboard(value, 'ru'); | ||
return (isCapitalize ? enteredValue[0].toUpperCase() + enteredValue.substr(1) : enteredValue) | ||
.replace(/[^\sа-яё-]/gi, '') | ||
.replace(/\s{2,}/g, ' '); | ||
}; | ||
/** | ||
* Возвращает TRUE, если проскролено до низа страницы | ||
*/ | ||
function hasScrolledToBottomOfPage() { | ||
var documentElement = document.documentElement; | ||
var offset = documentElement.scrollTop + window.innerHeight; | ||
var height = documentElement.offsetHeight; | ||
return offset >= height; | ||
} | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
var __assign = function() { | ||
__assign = Object.assign || function __assign(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
function __spreadArray(to, from) { | ||
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) | ||
to[j] = from[i]; | ||
return to; | ||
} | ||
/* eslint-disable no-param-reassign */ | ||
var NUMBER_REGEX = /^\d+$/; | ||
var SKIP_NODE_NAMES = ['', null, undefined]; | ||
var nodeNamesToPath = function (nodeNames) { | ||
return nodeNames.reduce(function (pathAcc, nodeName) { | ||
if (!SKIP_NODE_NAMES.includes(nodeName)) { | ||
if (nodeName === '*' || NUMBER_REGEX.test("" + nodeName)) { | ||
pathAcc += '[*]'; | ||
} | ||
else { | ||
if (pathAcc) { | ||
pathAcc += '.'; | ||
} | ||
pathAcc += nodeName; | ||
} | ||
} | ||
return pathAcc; | ||
}, ''); | ||
}; | ||
var INVALID_FILTER_CONFIG_VALUES = ['', null, undefined, true, false]; | ||
var VALID_REPLACE_CONFIG_TYPES = ['string', 'number', 'boolean', 'function']; | ||
var isReplacer = function (replacer) { | ||
return replacer === null || VALID_REPLACE_CONFIG_TYPES.includes(typeof replacer); | ||
}; | ||
var prepareConfig = function (_a) { | ||
var _b = _a.replace, replaceConfig = _b === void 0 ? {} : _b, _c = _a.filter, filterConfig = _c === void 0 ? [] : _c; | ||
var filteredReplaceConfig = Object.keys(replaceConfig).reduce(function (res, replaceConfigKey) { | ||
var replacer = replaceConfig[replaceConfigKey]; | ||
if (isReplacer(replacer)) { | ||
res[replaceConfigKey] = replacer; | ||
} | ||
return res; | ||
}, {}); | ||
var filteredFilterConfigObject = filterConfig.reduce(function (res, path) { | ||
var _a; | ||
if (INVALID_FILTER_CONFIG_VALUES.includes(path)) { | ||
return res; | ||
} | ||
return __assign(__assign({}, res), (_a = {}, _a[path] = true, _a)); | ||
}, {}); | ||
var paths = __spreadArray(__spreadArray([], Object.keys(filteredFilterConfigObject)), Object.keys(filteredReplaceConfig)); | ||
if (paths.length) { | ||
return { | ||
replaceConfig: filteredReplaceConfig, | ||
filterConfig: filteredFilterConfigObject, | ||
}; | ||
} | ||
throw new TypeError('required replace or filter in transformConfig'); | ||
}; | ||
var getReplaceValue = function (value, replacer) { | ||
if (isReplacer(replacer)) { | ||
return typeof replacer === 'function' ? replacer(value) : replacer; | ||
} | ||
return value; | ||
}; | ||
/* eslint-disable no-param-reassign */ | ||
// eslint-disable-next-line @typescript-eslint/naming-convention, no-underscore-dangle | ||
var _transformData = function (data, _a, parentPath) { | ||
var filterConfig = _a.filterConfig, replaceConfig = _a.replaceConfig; | ||
if (parentPath === void 0) { parentPath = ''; } | ||
return transform(data, function (result, value, key) { | ||
var currentPath = nodeNamesToPath([parentPath, key]); | ||
// Recurse into arrays and objects. | ||
if (Array.isArray(value) || isPlainObject(value)) { | ||
value = _transformData(value, { | ||
filterConfig: filterConfig, | ||
replaceConfig: replaceConfig, | ||
}, currentPath); | ||
} | ||
if (filterConfig[currentPath]) { | ||
return; | ||
} | ||
var newValue = getReplaceValue(value, replaceConfig[currentPath]); | ||
if (Array.isArray(result)) { | ||
result.push(newValue); | ||
return; | ||
} | ||
result[key] = newValue; | ||
}); | ||
}; | ||
/** | ||
* Преобразование полей объекта на основе конфига | ||
* | ||
* @param data {Object|Array} данные для преобразования | ||
* @param config {TransformConfig} конфиг с функциями преобразования и путей для фильтра | ||
*/ | ||
var transformData = function (data, config) { | ||
return _transformData(data, prepareConfig(config)); | ||
}; | ||
var transformDataUtils = { | ||
getReplaceValue: getReplaceValue, | ||
isReplacer: isReplacer, | ||
nodeNamesToPath: nodeNamesToPath, | ||
prepareConfig: prepareConfig, | ||
}; | ||
export { AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR, Locale, MMSP, NEGATIVE_SYMBOLS, THINSP, cropAccountNumber, formatAccount, formatAmount, formatFileSize, formatToRussian, getAllCurrencyCodes, getCountries, getCountriesHash, getCurrencySymbol, hasScrolledToBottomOfPage, isKeyboardLayout, isOverflown, isValidCardNumber, isValidEmail, keyboardLanguages, keyboardSwitcher, keyboardsLayouts, phoneNumber, pluralize, secondsToTime, splitAmount, switchToKeyboard, transformData, transformDataUtils }; | ||
export { cropAccountNumber } from './crop-account-number/util.js'; | ||
export { formatAccount } from './format-account/util.js'; | ||
export { AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR, MMSP, NEGATIVE_SYMBOLS, THINSP, formatAmount } from './format-amount/util.js'; | ||
export { formatFileSize } from './format-file-size/util.js'; | ||
export { Locale } from './format-file-size/locale.js'; | ||
export { phoneNumber } from './format-phone/index.js'; | ||
export { getAllCurrencyCodes } from './get-all-currency-codes/util.js'; | ||
export { getCountries, getCountriesHash } from './get-countries/util.js'; | ||
export { getCurrencySymbol } from './get-currency-symbol/util.js'; | ||
export { isOverflown } from './is-overflown/util.js'; | ||
export { pluralize } from './pluralize/util.js'; | ||
export { secondsToTime } from './seconds-to-time/util.js'; | ||
export { splitAmount } from './split-amount/util.js'; | ||
export { isValidCardNumber } from './is-valid-card-number/util.js'; | ||
export { isValidEmail } from './is-valid-email/util.js'; | ||
export { formatToRussian, isKeyboardLayout, keyboardLanguages, keyboardSwitcher, keyboardsLayouts, switchToKeyboard } from './keyboard-switcher/util.js'; | ||
export { hasScrolledToBottomOfPage } from './has-scrolled-to-bottom-of-page/util.js'; | ||
export { transformDataUtils } from './transform-data/index.js'; | ||
export { transformData } from './transform-data/util.js'; |
{ | ||
"name": "@alfalab/utils", | ||
"version": "1.16.0", | ||
"version": "1.17.0-next.2", | ||
"description": "common utils", | ||
@@ -13,5 +13,7 @@ "sideEffects": false, | ||
"scripts": { | ||
"build": "yarn build:ts && yarn build:dts", | ||
"build:ts": "rollup -c", | ||
"build:dts": "dts-bundle-generator --no-banner --config dts.json" | ||
"build": "yarn build:ts:es5 && yarn build:ts:es6 && yarn build:dts && yarn size", | ||
"build:ts:es5": "rollup --config './rollup.config.js'", | ||
"build:ts:es6": "rollup --config './rollup.config.esm.js'", | ||
"build:dts": "dts-bundle-generator --no-banner --no-check --config dts.json", | ||
"size": "yarn size-limit --json 2>&1 | grep -v '^$ ' > size-stat.json" | ||
}, | ||
@@ -23,8 +25,6 @@ "keywords": [], | ||
"@alfalab/data": "^1.8.0", | ||
"lodash": "4.17.21" | ||
"lodash": "^4.17.21" | ||
}, | ||
"devDependencies": { | ||
"@types/lodash": "4.14.182", | ||
"dts-bundle-generator": "^6.12.0", | ||
"rollup": "^2.38.0" | ||
"@types/lodash": "4.14.182" | ||
}, | ||
@@ -34,3 +34,3 @@ "publishConfig": { | ||
}, | ||
"gitHead": "81776918516e2a75f44ac1b04c177e3ca8f942e4" | ||
"gitHead": "10dd0711fab88c3173da9cd72abe50194559d021" | ||
} |
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
1
29
67435
1609
2
Updatedlodash@^4.17.21