0

I have a set of letters made from an array and I want to see if they have any characters from [a-z] in it.

let letterArr = ['a','d','w','e','r','q','y', 'w'];
let mySet = new Set(letterArr);

console.log(mySet.has('a')); //true
console.log(mySet.has('q')); //true

Could i search for a range of characters or numbers using has()?

newman
  • 421
  • 2
  • 9
  • 25

3 Answers3

1

No. Sets don't even allow for custom equalities, they don't do custom comparisons (as in "larger than a and smaller than z") either.

Of course you could easily test for each value in the range whether it is in the set, or for each value in the set whether it is in the range (whichever is faster), but this isn't very efficient. If you need to do this for large ranges and large sets, then you should consider your own Set implementation based on a search tree which can be searched for ranges with logarithmic time complexity.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

I would do it this way instead of set.

let letterArr = ['a','d','w','e','r','q','y', 'w'];
let str = letterArr.join('');

// Just to make sure this function exists
String.prototype.contains = function(x){ 
   return this.indexOf(x)!=-1;
}

console.log(str.contains('a')); //true
console.log(str.contains('q')); //true
console.log(str.contains('z')); //false
digitake
  • 846
  • 7
  • 16
  • 1
    Um `includes` instead of `contains` and it works without monkey-patching. – Jonas Wilms Apr 10 '18 at 20:05
  • Agreeing with Jonas W -- probably best to avoid mutating the `String` prototype, especially when [`includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) exists. – Alexander Nied Apr 10 '18 at 20:46
  • But there is still no way to check if a *range* exists using `include()`, right? – newman Apr 11 '18 at 15:30
  • @newman you can use regular expression for that. `"adwerqyw".match(/[f-k]/g)` this will return null because no chars in range f-k. – digitake Apr 12 '18 at 03:08
0
function mySet(char){

    let letterArr = ['a','d','w','e','r','q','y','w'].join(''),
        check = new RegExp('['+char+']','gi')

    return check.test(letterArr)

}

console.log(mySet("a")) // true
console.log(mySet("x")) // false
Ann MB
  • 146
  • 1
  • 13