@alfalab/utils
Advanced tools
Comparing version 1.6.0 to 1.7.0
@@ -6,2 +6,13 @@ # Change Log | ||
# [1.7.0](https://github.com/alfa-laboratory/utils/compare/@alfalab/utils@1.6.0...@alfalab/utils@1.7.0) (2021-12-23) | ||
### Features | ||
* add esm build ([#75](https://github.com/alfa-laboratory/utils/issues/75)) ([e48cc48](https://github.com/alfa-laboratory/utils/commit/e48cc487b5db1815cdaf10ad6639d42741f0d772)) | ||
# [1.6.0](https://github.com/alfa-laboratory/utils/compare/@alfalab/utils@1.5.1...@alfalab/utils@1.6.0) (2021-11-30) | ||
@@ -8,0 +19,0 @@ |
@@ -1,1 +0,320 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var r=require("@alfalab/data");var t=/^(\d{5})(\d{3})(\d)(\d{4})(\d{7})$/;var e=function(t){return r.currency.CURRENCY_SYMBOLS[t]},n=function(r,t,e,n){void 0===t&&(t=3),void 0===n&&(n=5);var o="\\B(?=(\\d{"+t+"})+(?!\\d))";return r.length<n?r:r.replace(new RegExp(o,"g"),e)},o=String.fromCharCode(8201),u=function(r,t){return[r,t].filter(Boolean).join(o)},a=["B","KB","MB","GB"],i=function(r){return r.replace(/\D+/g,"")};var c={format:function(r){var t=i(r).replace(/(\d)(\d{3})(\d{3})(\d{2})(\d{2})/,"$1 $2 $3-$4-$5");return"7"===t[0]?"+".concat(t):t},getRaw:i,mask:function(r){return r.substr(0,2)+" ··· ··· "+r.substr(r.length-5,r.length)}};var l=function(r){r[0];var t=r[1],e=r[2],n=r[3],o=r[4],u=r[5];return{name:t,iso2:e,dialCode:n,priority:o,areaCodes:null!=u?u:null}};function s(r,t){return void 0===t?r:(r+t).slice(-r.length)}var f=/^[-!#$%&'*+\/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])+$/;exports.AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR=",",exports.THINSP=o,exports.cropAccountNumber=function(r){return r?"··"+r.slice(-4):r},exports.formatAccount=function(r){return r?r.replace(t,"$1 $2 $3 $4 $5"):""},exports.formatAmount=function(r){var t=r.value,a=r.currency,i=r.minority,c=r.view,l=e(a);if(null===t)return{majorPart:"",minorPart:"",formatted:"",currencySymbol:l,formattedWithCurrency:u(t,l)};i=0===i?1:i;var s=Math.log(i)*Math.LOG10E,f=(Math.abs(t)/i).toFixed(s),d=f.split(".")[0],m=f.split(".")[1];"default"===c&&t%i==0&&(m="");var p=n(d,3,o,4),h=t<0?"−"+p:p,v=m?h+","+m:h;return{majorPart:h,minorPart:m,currencySymbol:l,formatted:v,formattedWithCurrency:u(v,l)}},exports.formatFileSize=function(r){for(var t=a.length-1,e=function(r){var t=Number(r);return Number.isNaN(t)?0:t}(r),n=0;e>=1024&&n<t;)e/=1024,n+=1;return function(r,t){return r>99&&t===a.length-1?"99+":""+Number(r.toFixed(2))}(e,n)+" "+a[n]},exports.getAllCurrencyCodes=function(){return Object.keys(r.currency.CURRENCY_SYMBOLS)},exports.getCountries=function(){return r.countries.map(l).sort((function(r,t){return r.name.localeCompare(t.name)}))},exports.getCountriesHash=function(){return r.countries.reduce((function(r,t){return r[t[2]]=l(t),r}),{})},exports.getCurrencySymbol=e,exports.hasScrolledToBottomOfPage=function(){var r=document.documentElement;return r.scrollTop+window.innerHeight>=r.offsetHeight},exports.isOverflown=function(r){return r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth},exports.isValidCardNumber=function(r){var t=0,e=r.replace(/\D/g,"");if(""===e)return!1;for(var n=0;n<e.length;n++){var o=parseInt(e[n],10);t+=0==n%2&&(o*=2)>9?o-9:o}return t%10==0},exports.isValidEmail=function(r){if(!r)return!1;var t=r.split("@");if(2!==t.length)return!1;var e=t[0],n=t[1],o=e.length>64,u=n.length>255;return!o&&!u&&(!n.split(".").some((function(r){return r.length>63}))&&f.test(r))},exports.phoneNumber=c,exports.pluralize=function(r,t,e,n){var o=Math.abs(r);return(o%=100)>=5&&o<=20?n:1===(o%=10)?t:o>=2&&o<=4?e:n},exports.secondsToTime=function(r){var t=Math.floor(r/60/60),e=Math.floor(r/60)%60,n=r-3600*t-60*e;return{hours:""+s("00",t),minutes:""+s("00",e),seconds:""+s("00",n)}},exports.splitAmount=n; | ||
'use strict'; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var data = require('@alfalab/data'); | ||
/** | ||
* Возвращает 4 последние цифры номера счёта в формате `··XXXX` | ||
*/ | ||
function cropAccountNumber(accountNumber) { | ||
if (!accountNumber) { | ||
return accountNumber; | ||
} | ||
return "\u00B7\u00B7" + accountNumber.slice(-4); | ||
} | ||
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 data.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; | ||
var NEGATIVE_AMOUNT_SYMBOL = '−'; | ||
var THINSP = String.fromCharCode(8201); //   | ||
var AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR = ','; | ||
var formatWithCurrency = function (value, currencySymbol) { | ||
return [value, currencySymbol].filter(Boolean).join(THINSP); | ||
}; | ||
/** | ||
* Форматирует значение суммы | ||
* согласно гайдлайну https://design.alfabank.ru/patterns/amount | ||
*/ | ||
var formatAmount = function (_a) { | ||
var value = _a.value, currency = _a.currency, minority = _a.minority, view = _a.view; | ||
var currencySymbol = getCurrencySymbol(currency); | ||
if (value === null) { | ||
return { | ||
majorPart: '', | ||
minorPart: '', | ||
formatted: '', | ||
currencySymbol: currencySymbol, | ||
formattedWithCurrency: formatWithCurrency(value, currencySymbol), | ||
}; | ||
} | ||
// 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 _b = valueAbsStr.split('.'), minorPart = _b[1]; | ||
if (view === 'default' && value % minority === 0) { | ||
minorPart = ''; | ||
} | ||
var majorPartSplitted = splitAmount(majorPart, AMOUNT_MAJOR_PART_SIZE, THINSP, AMOUNT_SPLIT_CODE_FROM); | ||
var majorPartFormatted = value < 0 ? NEGATIVE_AMOUNT_SYMBOL + majorPartSplitted : majorPartSplitted; | ||
var formattedValueStr = minorPart | ||
? majorPartFormatted + AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR + minorPart | ||
: majorPartFormatted; | ||
return { | ||
majorPart: majorPartFormatted, | ||
minorPart: minorPart, | ||
currencySymbol: currencySymbol, | ||
formatted: formattedValueStr, | ||
formattedWithCurrency: formatWithCurrency(formattedValueStr, currencySymbol), | ||
}; | ||
}; | ||
var UNITS = ['B', 'KB', 'MB', 'GB']; | ||
var humanizeNumberPartOfFileSize = function (value, factor) { | ||
var maxFactor = UNITS.length - 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) { | ||
var maxFactor = UNITS.length - 1; | ||
var humanSize = parseFileSize(fileSize); | ||
var factor = 0; | ||
while (humanSize >= 1024 && factor < maxFactor) { | ||
humanSize /= 1024; | ||
factor += 1; | ||
} | ||
return humanizeNumberPartOfFileSize(humanSize, factor) + " " + UNITS[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(data.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 data.countries.map(formatCountry).sort(function (a, b) { return a.name.localeCompare(b.name); }); | ||
}; | ||
var getCountriesHash = function () { | ||
return data.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; | ||
} | ||
function pluralize(number, one, two, five) { | ||
var n = Math.abs(number); | ||
n %= 100; | ||
if (n >= 5 && n <= 20) { | ||
return five; | ||
} | ||
n %= 10; | ||
if (n === 1) { | ||
return one; | ||
} | ||
if (n >= 2 && n <= 4) { | ||
return two; | ||
} | ||
return five; | ||
} | ||
/** | ||
* Приводит секунды к формату `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); | ||
} | ||
/** | ||
* Возвращает TRUE, если проскролено до низа страницы | ||
*/ | ||
function hasScrolledToBottomOfPage() { | ||
var documentElement = document.documentElement; | ||
var offset = documentElement.scrollTop + window.innerHeight; | ||
var height = documentElement.offsetHeight; | ||
return offset >= height; | ||
} | ||
exports.AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR = AMOUNT_MAJOR_MINOR_PARTS_SEPARATOR; | ||
exports.THINSP = THINSP; | ||
exports.cropAccountNumber = cropAccountNumber; | ||
exports.formatAccount = formatAccount; | ||
exports.formatAmount = formatAmount; | ||
exports.formatFileSize = formatFileSize; | ||
exports.getAllCurrencyCodes = getAllCurrencyCodes; | ||
exports.getCountries = getCountries; | ||
exports.getCountriesHash = getCountriesHash; | ||
exports.getCurrencySymbol = getCurrencySymbol; | ||
exports.hasScrolledToBottomOfPage = hasScrolledToBottomOfPage; | ||
exports.isOverflown = isOverflown; | ||
exports.isValidCardNumber = isValidCardNumber; | ||
exports.isValidEmail = isValidEmail; | ||
exports.phoneNumber = phoneNumber; | ||
exports.pluralize = pluralize; | ||
exports.secondsToTime = secondsToTime; | ||
exports.splitAmount = splitAmount; |
{ | ||
"name": "@alfalab/utils", | ||
"version": "1.6.0", | ||
"version": "1.7.0", | ||
"description": "common utils", | ||
"sideEffects": false, | ||
"main": "dist/index.js", | ||
"types": "dist/index.d.ts", | ||
"module": "dist/esm/index.js", | ||
"files": [ | ||
@@ -28,3 +30,3 @@ "dist" | ||
}, | ||
"gitHead": "4e02050d81ffe4bc4805d7745c2cb158dfd161a4" | ||
"gitHead": "a6952d4dc25629d92b0395f40cfcd0be6a09c53d" | ||
} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
36878
6
822
1
1