Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform case insensitive lookup in javascript set?

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"));
like image 630
anish Avatar asked Oct 21 '25 06:10

anish


2 Answers

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
like image 130
Jonas Wilms Avatar answered Oct 22 '25 20:10

Jonas Wilms


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.

like image 36
31piy Avatar answered Oct 22 '25 19:10

31piy