Skip to content

Commit

Permalink
refactor: add undefined return for getShortcode function
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianWoelki committed Oct 22, 2023
1 parent ad08f06 commit de9fca7
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 8 deletions.
11 changes: 6 additions & 5 deletions src/editor/icons-suggestion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ export default class SuggestionIcon extends EditorSuggest<string> {

// Store all emojis correspoding to the current query - parsing whitespaces and
// colons for shortcodes compatibility.
const emojisNameArray = Object.keys(emoji.shortNames).filter((e) =>
emoji.getShortcode(e).includes(queryLowerCase),
const emojisNameArray = Object.keys(emoji.shortNames).filter(
(e) => emoji.getShortcode(e)?.includes(queryLowerCase),
);

return [...iconsNameArray, ...emojisNameArray];
Expand All @@ -83,9 +83,10 @@ export default class SuggestionIcon extends EditorSuggest<string> {
el.innerHTML = `${iconObject.svgElement} <span>${value}</span>`;
} else {
// Suggest an emoji - display its shortcode version.
el.innerHTML = `<span>${value}</span> <span>${emoji.getShortcode(
value,
)}</span>`;
const shortcode = emoji.getShortcode(value);
if (shortcode) {
el.innerHTML = `<span>${value}</span> <span>${shortcode}</span>`;
}
}
}

Expand Down
5 changes: 5 additions & 0 deletions src/emoji.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,9 @@ describe('getShortcode', () => {
expect(emoji.getShortcode('🇺🇸')).toBe('flag_united_states');
expect(emoji.getShortcode('🏴󠁧󠁢󠁥󠁮󠁧󠁿')).toBe('flag_england');
});

it('should return `undefined` for invalid emojis', () => {
expect(emoji.getShortcode('hello')).toBe(undefined);
expect(emoji.getShortcode('123')).toBe(undefined);
});
});
6 changes: 3 additions & 3 deletions src/emoji.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1870,11 +1870,11 @@ const isEmoji = (str: string): boolean => {
* Gets the shortcode for a given emoji by the name of the emoji. This function replaces
* spaces with underscores and removes colons.
* @param key String to replace with shortcode.
* @returns String with shortcode.
* @returns String with shortcode, or `undefined` if no shortcode exists.
*/
const getShortcode = (key: string): string => {
const getShortcode = (key: string): string | undefined => {
// Removable of colons is necessary for the flag shortcodes.
return shortNames[key].replace(/\s/g, '_').replace(/:/g, '').toLowerCase();
return shortNames[key]?.replace(/\s/g, '_').replace(/:/g, '').toLowerCase();
};

export default {
Expand Down

0 comments on commit de9fca7

Please sign in to comment.