Created
March 16, 2023 08:15
-
-
Save AlexeyTsutsoev/17d18eee2787ff88976917fd1e339123 to your computer and use it in GitHub Desktop.
Formatter for cut string in the middle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { TCutOnMiddleArgs } from './types'; | |
/** | |
* compare first and second number | |
* @param firstLength number of cut result | |
* @param secondLength number of base string | |
* @returns boolean | |
*/ | |
const shouldBeCut = (firstLength: number = 0, secondLength: number) => { | |
return firstLength < secondLength; | |
}; | |
/** | |
* function cut string in the middle and insert placeholder between first and last counts | |
* Default Values: | |
* - `firstCount` -> 6 | |
* - `lastCount` -> 3 | |
* - `placeholder` -> ... | |
* | |
* @example | |
* const formatted = cutOnMiddle({ value: '12345678901234' }) // output: 123456...432 | |
* | |
* @example | |
* const formatted = cutOnMiddle({ value: 'QWERTY', firstCount: 1, lastCount: 1 }) | |
* // output: Q...Y | |
* | |
* @returns formatted string | |
*/ | |
export const cutOnMiddle = ({ | |
value, | |
firstCount = 6, | |
lastCount = 3, | |
placeholder = '...', | |
}: TCutOnMiddleArgs) => { | |
if (!value?.length) { | |
return value; | |
} | |
const cutLength = firstCount + lastCount + placeholder.length; | |
const isShouldBeCut = shouldBeCut(cutLength, value?.length); | |
if (!isShouldBeCut) { | |
return value; | |
} | |
return ( | |
value.slice(0, firstCount) + | |
placeholder + | |
value.slice(value.length - lastCount) | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type TCutOnMiddleArgs = { | |
value: string; | |
firstCount?: number; | |
lastCount?: number; | |
placeholder?: string; | |
}; | |
/** | |
* args for formatting strings and numbers with passed regex | |
*/ | |
export type TFormatWithRegexArgs = { | |
/** | |
* value to prepare | |
*/ | |
value: string | number; | |
/** | |
* regex for search | |
*/ | |
regex: RegExp | string; | |
/** | |
* string for replacing serched values | |
*/ | |
replaceValue: string; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment