chalk / ansi-regex

Regular expression for matching ANSI escape codes
MIT License
182 stars 78 forks source link

any reason this returns a function instead of just the regex? #9

Closed mafintosh closed 8 years ago

mafintosh commented 8 years ago

just curious :)

sindresorhus commented 8 years ago

It's a function so you can create multiple instances. Regexes with the global flag will have the .lastIndex property changed for each call to methods on the instance. Therefore reusing the instance with multiple calls will not work as expected for RegExp#test().

Qix- commented 8 years ago

@sindresorhus I'm not sure about this looking at MDN again. RegExp#exec() states they both increment lastIndex, but I believe that gets reset if the input string is different.

If anything, we could do a get() {} on it instead of return a function. I agree that returning a function is a strange and messy API.

Object.defineProperty(module, 'exports', {
    get: function () {
         return /.../g;
    },
    // ...
});
sindresorhus commented 8 years ago
const re = /\w+/g;

console.log(re.test('foo'));
//=> true
console.log(re.test('bar'));
//=> false
sindresorhus commented 8 years ago

I agree that returning a function is a strange and messy API.

I disagree. It's RegExp that is strange and messy. We could really use ImmutableRegExp. Actually, we could use immutable for most types.

Qix- commented 8 years ago

I tested this earlier and got something completely different I thought, which troubles me a bit. Going to have to test that again next time I'm on that particular box to see what's up.