0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

I have a Set with a whole bunch of things but I want to regex (or just check if part of a string exists) in the set.

I was thinking something like this.

mySet = new Set(["foo", "bar", "something SomethingIWant somethingelse"]);

/SomethingIWant/.test(mySet);
// false

mySet.forEach(myRegex(/SomethingIWant/));
// Doesn't work as I expect

Basically I need a function to iterate over a set(that I specify), regex testing each item (with a regex that I specify).

Does javascript allow this?

Trav Easton
  • 401
  • 2
  • 6
  • 17

2 Answers2

0

Yes, it looks like you are on the right track. This works for me:

let mySet = new Set(["foo", "bar", "something SomethingIWant somethingelse"]);

mySet.forEach(item => console.log( /SomethingIWant/.test(item) ) ); //returns false, false, true

// another way to accomplish the same thing
for(let item of mySet) {
  console.log( /SomethingIWant/.test(item) );
}

Some references: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set (see "Iterating Sets" section) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/forEach

Here's a more specific answer to your question:

function reduceSet(mySet, f, initial) {
    var result = initial;
    for (var v of mySet) result = f(result, v);
    return result;
}

reduceSet(mySet, (aggr, item) => {
    aggr = /SomethingIWant/.test(item);
    return aggr;
});
// => true

Set reduce implementation borrowed from: How to map/reduce/filter a Set in JavaScript?

I personally don't like modifying the prototypes of core JS objects, so I made it it's own function. However, it looks like reduce for Sets is slated for ES7 so you could safely polyfill it.

Community
  • 1
  • 1
ccnokes
  • 6,885
  • 5
  • 47
  • 54
  • That was excellent, thanks. In trying to make it a function, the `mySet.forEach(item => console.log( /SomethingIWant/.test(item) ) );` line returns undefined, do you have any idea why? – Trav Easton Jun 30 '16 at 06:07
  • because `forEach` returns undefined. Looking at your code below, what you really want is `reduce` but `Set` doesn't have a reduce method unfortunately. @TravEaston – ccnokes Jun 30 '16 at 16:18
  • Oh silly me, `some` would probably be better for your use case than reduce. An example implementation of `some` on a Set is also available here: http://stackoverflow.com/questions/33234666/how-to-map-reduce-filter-a-set-in-javascript. Anyways, I updated my answer with an example that reduces a set. – ccnokes Jun 30 '16 at 16:30
0

Finally figured it out with @ccnokes solution but wanted to provide my final result.

Set.prototype.regex = function(regex) {
    for(const item of this) {
       if (regex.test(item)) return true;
    }
    return false;
}

let mySet = new Set(["foo bar", "baz qux bar"]);

mySet.regex(/nothing/); // false
mySet.regex(/qux/);     // true
Trav Easton
  • 401
  • 2
  • 6
  • 17