Skip to content

Instantly share code, notes, and snippets.

@AlexeyTsutsoev
Created March 16, 2023 08:15
Show Gist options
  • Save AlexeyTsutsoev/17d18eee2787ff88976917fd1e339123 to your computer and use it in GitHub Desktop.
Save AlexeyTsutsoev/17d18eee2787ff88976917fd1e339123 to your computer and use it in GitHub Desktop.
Formatter for cut string in the middle
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)
);
};
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