Skip to content

Instantly share code, notes, and snippets.

@jeremiah-ang
Created June 20, 2017 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremiah-ang/e6fcbb195e1d22114a4b236dab43a8db to your computer and use it in GitHub Desktop.
Save jeremiah-ang/e6fcbb195e1d22114a4b236dab43a8db to your computer and use it in GitHub Desktop.
Few functions to help search for a matches of a substring in an array
var arr = [
'1 Chronicles', '1 Corinthians', '1 John', '1 Kings',
'1 Peter', '1 Samuel', '1 Thessalonians', '1 Timothy',
'2 Chronicles', '2 Corinthians', '2 John', '2 Kings',
'2 Peter', '2 Samuel', '2 Thessalonians', '2 Timothy',
'3 John', 'Acts', 'Amos', 'Colossians',
'Daniel',
'Deuteronomy', 'Ecclesiastes', 'Ephesians', 'Esther',
'Exodus', 'Ezekiel', 'Ezra', 'Galatians',
'Genesis', 'Habakkuk', 'Haggai', 'Hebrews',
'Hosea', 'Isaiah', 'James', 'Jeremiah',
'Job', 'Joel', 'John', 'Jonah',
'Joshua', 'Jude', 'Judges', 'Lamentations',
'Leviticus', 'Luke', 'Malachi', 'Mark',
'Matthew', 'Micah', 'Nahum', 'Nehemiah',
'Numbers', 'Obadiah', 'Philemon', 'Philippians',
'Proverbs', 'Psalm', 'Revelation', 'Romans',
'Ruth', 'Song of Solomon', 'Titus', 'Zechariah',
'Zephaniah' ];
var search = "Eze";
function preprocess (arr) {
if (typeof arr == "string") {
return arr.replace (/\s+/g, "+").toLowerCase()
}
for (var i in arr) {
arr[i] = preprocess(arr[i]);
}
}
function postprocess (arr) {
if (typeof arr == "string") {
return arr
.replace (/(\+\w)/g, function ($1) {
return " " + $1.charAt(1).toUpperCase();
})
.replace (/[a-zA-Z]/, function ($2) {
return $2.toUpperCase();
});
}
for (var i in arr) {
arr[i] = postprocess(arr[i]);
}
}
function make_radix_tree (arr, prefix="") {
if (!Array.isArray(arr)) {
return arr;
}
var trix = {};
for (var i in arr) {
var str = arr[i];
var key = str.charAt(0);
if (str.length > 1) {
var str = str.substr(1);
if (!Array.isArray(trix[key]))
trix[key] = [];
trix[key].push(str);
} else {
trix[key] = prefix + str;
}
}
for (var j in trix) {
trix[j] = make_radix_tree(trix[j], prefix + j);
}
return trix;
}
function compress_radix_tree (trix) {
if (typeof trix == "string") {
return [trix];
}
var compressed = [];
for (var key in trix) {
compressed = compressed.concat(compress_radix_tree(trix[key]));
}
return compressed
}
function findPrefix (prefix, arr) {
preprocess(arr);
prefix = preprocess(prefix);
var trix = make_radix_tree(arr);
var subtrix;
for (var i = 0; i < prefix.length; i++) {
subtrix = trix[prefix[i]]
if (subtrix == null) {
// no such prefix
// return best matches
return compress_radix_tree(trix)
}
trix = subtrix;
}
var result;
if (typeof trix == "object") {
result = compress_radix_tree(trix);
} else result = trix;
postprocess (result);
return result;
}
console.log(findPrefix(search, arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment