So this is a no-brainer.
if (typeof URL.parse != 'function') {URL.parse = function (_s){let _ret; try { _ret = new URL(_s)} catch {}; return _ret} } ;
const tryNew = (f, ...a) => {
try {
return new f(...a);
} catch(x) {
return undefined;
}
};
const myUrl = tryNew(URL, 'http://example.com/');I don't get why JS devs like to whinge about the smallest things. And we get stuff like leftPad because of huge aversion to writing utility functions.
Does every dev need to write the same line now? Or should your one-liner be a library?
The basics that everybody needs, should be standardized in the standard library.
Yes.
> Or should your one-liner be a library?
Definitely not.
Particularly if I can write the one-liner faster than it takes one to search, check, include and install the library.
On the other hand, you don't want to be Java, where List.Last took until Java 21 to get implemented. It's not hard to make a wrapper function, but it's really annoying to clutter your code with helper functions where the native API should help you.
In this specific instance, I agree with the new spec: most constructors for native Javascript types don't throw, so neither should the URL constructor. However, the try/catch isn't exactly the problem some people seem to think it is. It's a minor annoyance that apparently annoyed at least three browser teams enough to come up with a new API. In other circumstances, I hope the API spec won't be extended as easily.
Can you explain how helpers create exploits? Are there any examples?
It's easier to secure a JIT with 100 methods than it is to secure a JIT with a thousand.