Skip to content

Instantly share code, notes, and snippets.

@Cologler
Last active September 7, 2017 03:49
Show Gist options
  • Save Cologler/aa6161ea54b030df480ef0a24d237fe6 to your computer and use it in GitHub Desktop.
Save Cologler/aa6161ea54b030df480ef0a24d237fe6 to your computer and use it in GitHub Desktop.
#javascript_lib #user_script_lib
// ==UserScript==
// @name StringSearcherMap
// @namespace https://github.com/cologler/
// @version 0.1
// @description try to take over the world!
// @author cologler
// @grant none
// ==/UserScript==
class StringSearcherMap {
constructor(table = null) {
let data = {};
let minKey = -1;
this.add = function(key, value) {
if (typeof key !== 'string') {
throw 'key must be string';
}
if (key) {
let ch = key[0];
let ls = data[ch];
if (ls === undefined) {
data[ch] = ls = [];
}
let isExists = false;
for (let i = 0; i < ls.length; i++) {
let entry = ls[i];
if (entry.key == key) {
entry.value = value;
isExists = true;
break;
}
}
if (!isExists) {
ls.push({
key: key,
value: value
});
}
minKey = minKey == -1 ? key.length : Math.min(minKey, key.length);
}
};
this.remove = function(key) {
throw 'not impl remove method.';
};
this.sort = function() {
Object.values(data).forEach(z => z.sort((x, y) => y.key.length - x.key.length));
};
this.match = function(str) {
let results = [];
if (str && minKey !== -1) {
let lastStart = 0;
let len = str.length - minKey + 1;
for (let i = 0; i < len; i++) {
let ch = str[i];
let ls = data[ch];
if (ls) {
for (let j = 0; j < ls.length; j ++) {
let item = ls[j];
if (str.startsWith(item.key, i)) {
if (lastStart < i) {
results.push({
type: 0,
text: str.substr(lastStart, i - lastStart)
});
}
results.push({
type: 1,
text: item.key,
data: item.value
});
i += item.key.length;
lastStart = i;
i--;
break;
}
}
}
}
if (lastStart < str.length) {
results.push({
type: 0,
text: str.substr(lastStart, str.length - lastStart)
});
}
} else {
results.push({
type: 0,
text: str || ''
});
}
return results;
};
if (table) {
let self = this;
Object.keys(table).forEach(key => {
self.add(key, table[key]);
});
}
}
}

This lib can work for highlight keywords or more.

// @require            https://greasyfork.org/scripts/32209-stringsearchermap/code/StringSearcherMap.js

let map = new StringSearcherMap();
map.add('50', 1);
json_equals(map.match('8504'), [
    { type: 0, text: '8' },
    { type: 1, text: '50', data: 1 },
    { type: 0, text: '4' }
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment