Created
September 12, 2019 19:25
-
-
Save beefchimi/4cddff89d36f2eac6ac46db2cc712d68 to your computer and use it in GitHub Desktop.
Format React key
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 const regExpCommonCharacters = new RegExp(/[^\w]/gim); | |
const INDEX_DELIMITER = '-'; | |
const MAX_CHARACTER_LENGTH = 100; | |
export function formatReactKey(key: string, index: number | null = null) { | |
const hasIndex = index || index === 0; | |
const transformedKey = [ | |
...key | |
.toLowerCase() | |
.replace(regExpCommonCharacters, '') | |
.substring( | |
0, | |
hasIndex | |
? MAX_CHARACTER_LENGTH - | |
(INDEX_DELIMITER.length + index!.toString().length) | |
: MAX_CHARACTER_LENGTH, | |
), | |
] | |
.map((character) => | |
Math.random() > 0.5 ? character.toUpperCase() : character, | |
) | |
.join(''); | |
return hasIndex | |
? `${transformedKey}${INDEX_DELIMITER}${index}` | |
: transformedKey; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment