|
| 1 | +import type { |
| 2 | + BlocksType, |
| 3 | + DelimiterType, |
| 4 | + GetFormattedValueProps, |
| 5 | + StripDelimitersProps, |
| 6 | +} from './types' |
| 7 | + |
| 8 | +// const test = (): string => { |
| 9 | +// return 'test-eslint' |
| 10 | +// } |
| 11 | + |
| 12 | +export function isString(value: any): value is string { |
| 13 | + return typeof value === 'string' |
| 14 | +} |
| 15 | + |
| 16 | +export function stripNonNumeric(value: string): string { |
| 17 | + return value.replace(/\D/g, '') |
| 18 | +} |
| 19 | + |
| 20 | +export function getMaxLength(blocks: BlocksType): number { |
| 21 | + return blocks.reduce((previous: number, current: number) => previous + current, 0) |
| 22 | +} |
| 23 | + |
| 24 | +export function headStr(str: string, length: number): string { |
| 25 | + return str.slice(0, length) |
| 26 | +} |
| 27 | + |
| 28 | +export function getDelimiterRegexByDelimiter(delimiter: string): RegExp { |
| 29 | + return new RegExp(delimiter.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'), 'g') |
| 30 | +} |
| 31 | + |
| 32 | +export function stripDelimiters({ |
| 33 | + value, |
| 34 | + delimiters, |
| 35 | +}: StripDelimitersProps): string { |
| 36 | + delimiters.forEach((current: DelimiterType) => { |
| 37 | + current.split('').forEach((letter) => { |
| 38 | + value = value.replace(getDelimiterRegexByDelimiter(letter), '') |
| 39 | + }) |
| 40 | + }) |
| 41 | + |
| 42 | + return value |
| 43 | +} |
| 44 | + |
| 45 | +export function getFormattedValue({ |
| 46 | + value, |
| 47 | + blocks, |
| 48 | + delimiter = '', |
| 49 | + delimiters = [], |
| 50 | + delimiterLazyShow = false, |
| 51 | +}: GetFormattedValueProps): string { |
| 52 | + let result = '' |
| 53 | + let valueRemaining = value |
| 54 | + let currentDelimiter = '' |
| 55 | + |
| 56 | + blocks.forEach((length: number, index: number) => { |
| 57 | + if (valueRemaining.length > 0) { |
| 58 | + const sub = valueRemaining.slice(0, length) |
| 59 | + const rest = valueRemaining.slice(length) |
| 60 | + |
| 61 | + if (delimiters.length > 0) { |
| 62 | + currentDelimiter |
| 63 | + = delimiters[delimiterLazyShow ? index - 1 : index] ?? currentDelimiter |
| 64 | + } |
| 65 | + else { |
| 66 | + currentDelimiter = delimiter |
| 67 | + } |
| 68 | + |
| 69 | + if (delimiterLazyShow) { |
| 70 | + if (index > 0) { |
| 71 | + result += currentDelimiter |
| 72 | + } |
| 73 | + |
| 74 | + result += sub |
| 75 | + } |
| 76 | + else { |
| 77 | + result += sub |
| 78 | + |
| 79 | + if (sub.length === length && index < blocks.length - 1) { |
| 80 | + result += currentDelimiter |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + // update remaining string |
| 85 | + valueRemaining = rest |
| 86 | + } |
| 87 | + }) |
| 88 | + |
| 89 | + return result |
| 90 | +} |
0 commit comments