culori
culori copied to clipboard
parse(): thow an error when parsing is unsuccessful
It would be very practical, if parse would throw an error if it was not successful in parsing a color.
try {
const color = culori.parse('something');
console.log({color}); // {{ color: undefined }}
} catch (error) {
console.error(error);
}
The only way I can do this now is check for undefined
.
I'd find it very practical to get something like:
throw new Error(
`parse() must be an object or a valid color string but \`${arguments}\` were given.`
);
Hi @meodai, thanks for bringing this up.
I was just thinking the other day that I should make explicit in the API Reference that it's a convention throughout the Culori API for methods to return undefined
when they can't produce a valid color, and that a chain of methods, eg. formatHex(hsl(rgb('tomato')))
should not break on unparseable strings.
This makes it nicer to code in environments where you primarily work with expressions, such as Observable notebooks, but also in regular code, where you can casually insert your own parsers or other fallbacks:
const myColor = culori.parse(string) || myFancyParser(string) || culori.rgb('#0000');
if (myColor) {
// do something with `myColor`
}
I don't believe parsing an invalid string should throw (and it wouldn't have much useful feedback other than that the string is not understood), but I will look into throwing TypeError
s when the API is invoked with the wrong types of arguments. (Also JSDoc / TS type definitions #128 may help with IDE autocompletion).
It would also maybe make sense to have a way to switch the whole API from the return undefined
paradigm to be throw
-based.
@danburzo ah ok I get it. But maybe having a isValid()
method then?
I am working on a class that uses culori, I want to make sure all the colors that are passed in, can be parsed.
isValid('red') // => true
isValid('jeronimo') // => false
or maybe validate(color)
: that would return an error code and what part did not work
validate(rgb(260,0,0)
) => error: RGB component range is between 0 - 255.
PS: Don't see this as an issue, more of a suggestion, I am simply testing for undefined now