Skip to content

Instantly share code, notes, and snippets.

@TimothyGu
Last active August 29, 2015 14:16
Show Gist options
  • Save TimothyGu/8ca818ee433828e7f02a to your computer and use it in GitHub Desktop.
Save TimothyGu/8ca818ee433828e7f02a to your computer and use it in GitHub Desktop.

Mini search engine written in JavaScript for a web page

For Gustavo E. Zertuche.

Happy birthday.

Licensed under the MIT license.

// Copyright © 2015 Tiancheng "Timothy" Gu
// Licensed under the MIT License
// No semicolons.
// Mini search engine
// What this does is:
// it searches the entire HTML for a tag with `tagName` with `needle`, and
// then returns an array of strings with that content.
// Gustavo, IIRC you want a search engine that searches the <p>'s and then
// return the *title* of the article. It is not possible without id's.
function search (needle, tagName) {
// -1. If no needle is specified return nothing.
if (!needle) return []
// 0. Default to <p>
tagName = tagName || 'p'
// 1. Get all tags with this tag name:
var elements = document.getElementsByTagName(tagName)
// 2. Convert this HTMLCollection to an Array. How this works
// is too high-level for you right now. Ask me again when you
// have learned protpotypes.
elements = Array.prototype.slice.apply(elements)
// 3. Grab the text of the elements and put them in elementTexts
var haystack = elements.map(function (element) {
return element.textContent
})
// 4. Search for the content
var textsWithKeyword = haystack.filter(function (t) {
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
// for how indexOf works.
// Basically it just searches the string (`t` in this case) for the text
// passed in (`needle`), and return either the index (i.e. the position
// of the first occurance of the searched content) or if it is not found,
// returns `-1`.
var index = t.indexOf(needle)
, found = index !== -1
return found
})
return textsWithKeyword
}
// Same thing, but written (a lot) more concisely, without the extra variables
function search (needle, tagName) {
if (!needle) return []
return Array.prototype.slice.apply(
document.getElementsByTagName(tagName || 'p')
).map(function (e){
return e.textContent
}).filter(function (t) {
return t.indexOf(needle) !== -1
})
}
// This version returns Array of Nodes of HTML instead of Strings (so that
// data like id's and classes are kept). You can then use these ids to
// lookup titles, if you add titles.
function search (needle, tagName) {
if (!needle) return []
return Array.prototype.slice.apply(
document.getElementsByTagName(tagName || 'p')
).filter(function (e){
return e.textContent.indexOf(needle) !== -1
})
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Demo</title>
</head>
<body>
<!--Filler text-->
<p>Eius, exercitationem quos repellendus dolorum architecto doloribus quo corporis minus. Quod, iure, voluptatem animi esse doloribus odio vitae perspiciatis iste nobis maxime!</p>
<p>Ad, ea, expedita, possimus ut nobis minus laborum maxime magni modi repudiandae alias et doloremque numquam dolore eligendi totam molestiae optio explicabo?</p>
<p>Vel, totam iste soluta eum cupiditate harum nihil tempora ipsam dolorum possimus tempore minus accusamus sequi a unde! Maiores iusto excepturi totam!</p>
<p>Neque vitae dolorum soluta totam officiis praesentium odit excepturi similique consectetur temporibus. Officiis, quos modi voluptas libero consectetur tempore veritatis harum facere!</p>
<p>Perspiciatis, illo, error, velit dignissimos nisi delectus provident inventore optio natus tempora maiores expedita eveniet tempore fugiat repellat rem iure iusto quos.</p>
<p>Fugit, nam, similique sit nobis architecto odit neque error delectus cupiditate aut perferendis voluptas iste ex totam reiciendis excepturi rem. Officia, hic.</p>
<p>Est, at id delectus in quis neque expedita. Itaque, ullam, tempora, optio ratione quaerat quo impedit vitae voluptate eveniet reprehenderit delectus asperiores!</p>
<p>Ipsum, quam, dicta, fugiat perspiciatis culpa minus eligendi libero necessitatibus dolores soluta iusto explicabo labore aliquam nisi pariatur delectus corrupti ea velit!</p>
<p>Similique, mollitia, voluptate, ab excepturi suscipit quis molestias quo ipsum magnam beatae vel corporis neque dolorem repudiandae hic sint maxime ratione cum?</p>
<p>Itaque, praesentium tenetur sequi laborum ex ut autem obcaecati a officia magnam similique illum. Delectus, placeat, animi incidunt dolor porro hic cum?</p>
<pre id="results">
Results will go here
</pre>
<div>
<button onclick="askForSearch()">Search Something (with prompt)</button>
</div>
<div>
<input id="input" type="text" class="form-control" placeholder="What do you want to search today">
<button onclick="searchFromTextbox()">Search!</button>
</div>
<script>
// Copied from the file above (index.js)
function search (needle, tagName) {
// -1. If no needle is specified return nothing.
if (!needle) return []
// 0. Default to <p>
tagName = tagName || 'p'
// 1. Get all tags with this tag name:
var elements = document.getElementsByTagName(tagName)
// 2. Convert this HTMLCollection to an Array. How this works
// is too high-level for you right now. Ask me again when you
// have learned prototypes.
elements = Array.prototype.slice.apply(elements)
// 3. Grab the text of the elements and put them in elementTexts
var haystack = elements.map(function (element) {
return element.textContent
})
// 4. Search for the content
var textsWithKeyword = haystack.filter(function (t) {
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
// for how indexOf works.
// Basically it just searches the string (`t` in this case) for the text
// passed in (`needle`), and return either the index (i.e. the position
// of the first occurance of the searched content) or if it is not found,
// returns `-1`.
var index = t.indexOf(needle)
, found = index !== -1
return found
})
return textsWithKeyword
}
// Get the elements we need
var // preformatted text box to put our results in
e = document.getElementById('results')
, // input textbox
i = document.getElementById('input')
function askForSearch () {
// Prompt
var needle = prompt('What would you like to search?')
// Search
var results = search(needle)
// Make the results in JSON format suitable to be printed to screen
// And inject the contents to the `results` text box
// The null is used to preserve default behavior, while ' ' is for
// pretty-printed output with proper indentation.
e.textContent = JSON.stringify(results, null, ' ')
}
function searchFromTextbox () {
// Get text content of the textbox
var needle = i.value
// Search
var results = search(needle)
// Make the results in JSON format suitable to be printed to screen
// And inject the contents to the `results` text box
// The null is used to preserve default behavior, while ' ' is for
// pretty-printed output with proper indentation.
e.textContent = JSON.stringify(results, null, ' ')
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment