Created
March 15, 2014 01:34
-
-
Save Apophenia/9560558 to your computer and use it in GitHub Desktop.
"20 minute" string search challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lol global | |
var index = {}; | |
function add(content, uid) { | |
contentArray = content.split(" "); | |
index[uid] = {}; | |
for (i = 0, len = contentArray.length; i<len; i++) { | |
index[uid][contentArray[i]] = true; | |
} | |
} | |
function search(query) { | |
var result = []; | |
queryArray = query.trim().split(" "); | |
for (var key in index) { | |
if (containsAll(queryArray, index[key])) { | |
result.push(key); | |
} | |
} | |
return result; | |
} | |
function containsAll(splitQuery, page) { | |
for (j = 0, len = splitQuery.length; j<len; j++) { | |
if (!contains(splitQuery[j], page)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function contains(word, page) { | |
return (!!page[word]) | |
} | |
// TESTS | |
add("puppies kittens", 9); | |
add("kittens", 10); | |
add("puppies", 8); | |
add("dog cat", 6); | |
console.log("printing index"); | |
console.log(index); | |
console.log("just puppies:") | |
console.log(search(" puppies")); | |
console.log("just kittens"); | |
console.log(search("kittens ")); | |
console.log("puppies and kittens:"); | |
console.log(search("puppies kittens")); | |
console.log(search("hot dog")); | |
console.log(search("cat dog")); | |
console.log(search("puppies")); | |
console.log("OLD TESTS better return true or we're really in trouble :c"); | |
console.log(contains("dog",{dog: true})); | |
console.log(contains("dog",{hello: true, is: true, dog: true})); | |
console.log(containsAll(["my","milkshake"],{my: true, milkshake: true, brings: true, all: true})); | |
console.log(containsAll(["milkshake"],{milkshake: "milkshake"})); |
I don't know javascript very well, but the code looks pretty readable.
// lol global
var index = {};
(at first I thought index was a special js keyword, haha)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I removed the contains function, added var to the for loop variables, and renamed a few variables. But looks great!
https://gist.github.com/paulvstheworld/9560591