JSFiddle - React, Tailwind, and code Playground
by ifandelse
HTML
<ul id="regex"></ul>
<hr/>
CSS
.binding {
color: blue;
}
.topic {
color: green;
}
JavaScript
var bindingsResolver = {
cache: {},
compare: function(binding, topic) {
if (this.cache[topic] && this.cache[topic][binding]) {
return true;
}
var pattern = ("^" + binding.replace(/\./g, "\\.") // escape actual periods
.replace(/\*/g, "[A-Z,a-z,0-9]*") // asterisks match any alpha-numeric 'word'
.replace(/#/g, ".*") + "$") // hash matches 'n' # of words (+ optional on start/end of topic)
.replace("\\..*$", "(\\..*)*$") // fix end of topic matching on hash wildcards
.replace("^.*\\.", "^(.*\\.)*"); // fix beginning of topic matching on hash wildcards
var rgx = new RegExp(pattern);
var result = rgx.test(topic);
if (result) {
if (!this.cache[topic]) {
this.cache[topic] = {};
}
this.cache[topic][binding] = true;
}
$('#regex').append("<li>REGEX: " + rgx + "</li>"); // HERE FOR DEBUG IN JSFIDDLE ONLY
return result;
},
reset: function() {
this.cache = {};
}
};
var expectations = [
{
binding: "Home.*",
topic: "Home.Boy",
shouldMatch: true},
{
binding: "Home.*",
topic: "Home.Sweet.Home",
shouldMatch: false},
{
binding: "*.Sweet.*",
topic: "Home.Sweet.Home",
shouldMatch: true},
{
binding: "*.Sweet.*",
topic: "Cubicle.Sweet.Cubicle",
shouldMatch: true},
{
binding: "*.Sweet.*",
topic: "Something.Sweet.And.Salty",
shouldMatch: false},
{
binding: "Home.#",
topic: "Home.Boy",
shouldMatch: true},
{
binding: "Home.#",
topic: "Home.Sweet.Home",
shouldMatch: true},
{
binding: "Home.#",
topic: "Home",
shouldMatch: true},
{
binding: "#.Home",
topic: "Home.Sweet.Home",
shouldMatch: true},
{
binding: "#.Home",
topic: "There.Is.No.Place.Like.Home",
shouldMatch: true},
{
binding: "#.Home",
topic:...