Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question around choice of factory #105

Closed
mfbx9da4 opened this issue Feb 17, 2023 · 2 comments
Closed

Question around choice of factory #105

mfbx9da4 opened this issue Feb 17, 2023 · 2 comments

Comments

@mfbx9da4
Copy link

mfbx9da4 commented Feb 17, 2023

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
Copy link
Owner

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 #19 (comment)

@mfbx9da4
Copy link
Author

mfbx9da4 commented Feb 17, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants