Last active
June 5, 2024 19:36
-
-
Save darcher-/110f59a24b5c0c746d5ad5f3a9ff9d74 to your computer and use it in GitHub Desktop.
Compare the first character(s) of the provided context against one or more symbols
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
//? an easy to follow, abstracted approach | |
/** | |
* Compares first character of string against a character | |
* @param {string} reference | |
* @returns {(character: string) => boolean} | |
*/ | |
function startsWithCharacter(reference) { | |
return character => reference.startsWith( | |
character | |
); | |
} | |
/** | |
* Compares characters against a strings first character | |
* @param {string} reference | |
* @returns {(characters: string[]) => boolean} | |
*/ | |
function startsWithCharacters(reference) { | |
return characters => characters.some( | |
startsWithCharacter(reference) | |
) | |
} | |
/** | |
* Compares one or more characters against the first character in a string | |
* @param {string} reference | |
* @returns {(variedInput: string|string[]) => boolean} | |
*/ | |
function startsWithSymbol(reference) { | |
return variedInput => startsWithCharacters(reference)( | |
useOrWrapInArray(variedInput) | |
) | |
} | |
//? ...an alternative "all in one" solution: shorter but less understandable | |
/** | |
* Compares one or more characters against the first character in a string | |
* @param {string} reference | |
* @returns {(variedInput: string|string[]) => boolean} | |
*/ | |
function startsWithSymbols(reference) { | |
return variedInput => (useOrWrapInArray(variedInput)) | |
.includes(Array.from(reference)[0]) | |
} | |
//? utility methods for reuse | |
/** | |
* Use array or wrap value in an array. | |
* @param {*|*[]} - input value(s) | |
* @returns {*[]} | |
*/ | |
function useOrWrapInArray(variedInput) { | |
return !Array.isArray(variedInput) | |
? [variedInput] | |
: variedInput; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment