mathiasbynens / emoji-regex

A regular expression to match all Emoji-only symbols as per the Unicode Standard.
https://mths.be/emoji-regex
MIT License
1.72k stars 175 forks source link

Question around choice of factory #105

Closed mfbx9da4 closed 1 year ago

mfbx9da4 commented 1 year ago

I noticed you've decided to use a factory pattern rather just a plain export. eg.

export const emojiRegex = /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u.....

Presumably this was decided because there is a cost to the JS runtime compiling the regex upfront which doesn't need to happen if it's contained in the function, this would only happen when the function is called?

Would it make more sense to have a singleton API e.g

let _regex
export const emojiRegex = () => {
   if (_regex === undefined) _regex = /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u.....
  return _regex
}

Or is the cost for compiling the regex only paid the first time the factory is called and subsequent calls are negligible?

mathiasbynens commented 1 year ago

Global RegExps are stateful through the .lastIndex property. Exporting a function that gives consumers a fresh RegExp means they don't have to worry about this.

Also see https://github.com/mathiasbynens/emoji-regex/issues/19#issuecomment-303298828

mfbx9da4 commented 1 year ago

Oooo TIL regex's in JS are stateful 🤯 god knows how many bugs I created without thinking about this