UNPKG

@andreasnicolaou/emoji-x-converter

Version:

A TypeScript library to convert between emojis and their textual descriptions across different languages using customizable mappings.

38 lines (37 loc) 1.63 kB
import { emojiXLoader } from './data/loader'; export class EmojiXConverter { static EMOJI_PREFIX = '\xA9\xAE\xE2\xE3\xF0'; static instances = Object.create(EmojiXConverter.prototype); id; map; static getInstance(id, direction = 'CONVERT_EMOJI') { const key = `${id}-${direction.toLowerCase()}`; if (!this.instances[key]) { this.instances[key] = this.createInstance(id, direction); } return this.instances[key]; } static createInstance(id, direction) { if (!Object.keys(emojiXLoader).includes(id)) { throw new Error(`Language map for "${id}" not found. Available IDs: ${Object.keys(emojiXLoader).join(', ')}`); } const instance = Object.create(EmojiXConverter.prototype); instance.id = id; instance.map = emojiXLoader[id]; if (direction === 'CONVERT_DESCRIPTION') { instance.map = Object.fromEntries(Object.entries(instance.map).map(([emoji, description]) => [`:${description}:`, emoji])); } return instance; } convertText(input) { const emojiKeys = Object.keys(this.map).sort((a, b) => b.length - a.length); const regex = new RegExp(emojiKeys.join('|'), 'g'); const emojiPrefix = input.startsWith(Object.keys(this.map)[0]) ? ':' : EmojiXConverter.EMOJI_PREFIX; if (/^[\s\S]*$/u.test(input)) { return input.length === input.split('').findIndex((char) => emojiPrefix.includes(char)) ? input : input.replace(regex, (match) => this.map[match] || match); } return input; } }