How to perform case-insensitve lookup in javascript's set
?
I have a situation where I have a set of allowed strings which doesn't ensure what case they would be in. I need to validate a user input against that set. How can I achieve this?
const countries = new Set();
countries.add("USA");
countries.add("japan");
// returns false, but is there any way I could get
//`my set to ignore case and return true?`
console.log(countries.has("usa"));
console.log(countries.has("USA"));
Just always call .toLowerCase
on the string before you add it or before performing a .has
check. For sure you can also abstract that into a class (if thats really necessary):
class CaseInsensitiveSet extends Set {
constructor(values) {
super(Array.from(values, it => it.toLowerCase()));
}
add(str) {
return super.add(str.toLowerCase());
}
has(str) {
return super.has(str.toLowerCase());
}
delete(str) {
return super.delete(str.toLowerCase());
}
}
const countries = new CaseInsensitiveSet([
"Usa",
]);
console.log(countries.has("usa")); // true
The short answer is "no". has
uses SameValueZero algorithm to seek for a value's existence. See the comparison table here.
If performance is not a concern, you can try two searches, one with uppercased value, and one with lowercased value, and decide whether the value actually exists.
And the better approach would be to always insert the values by converting them to uppercase/lowercase and match accordingly for existence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With