xxxxxxxxxx
80
/**
* HashMap example
* by Daniel Shiffman.
*
* This example demonstrates how to use a JavaScript object to store
* a collection of objects referenced by a key. This is much like an array,
* only instead of accessing elements with a numeric index, we use a String.
* If you are familiar with associative arrays from other languages,
* this is the same idea.
*
* A simpler example is CountingStrings which uses a simpler object
* Here we we want to pair a String with a custom
* object, in this case a "Word" object that stores two numbers.
*
* In this example, words that appear in one book (Dracula) only are colored white
* while words the other (Frankenstein) are colored black.
*/
let words = {};
let linesDracula;
let linesFranken;
function preload() {
linesDracula = loadStrings("data/dracula.txt")
linesFranken = loadStrings("data/frankenstein.txt")
}
function setup() {
createCanvas(640, 360);
// Load two files
loadFile(linesDracula, "dracula");
loadFile(linesFranken, "frankenstein");
}
function draw() {
background(126);
// Show words
let keys = Object.keys(words);
for (let key of keys) {
let w = words[key];
if (w.qualify()) {
w.display();
w.move();
}
}
}
// Load a file
function loadFile(lines, file) {
let allText = join(lines, " ").toLowerCase();
let tokens = allText.split(/[.?!\s]+/);
for (let s of tokens) {
// Is the word in the HashMap
if (words[s]) {
// Get the word object and increase the count
// Which book am I loading?
if (file == "dracula") {
words[s].incrementDracula();
} else if (file == "frankenstein") {
words[s].incrementFranken();
}
} else {
// Otherwise make a new word
let w = new Word(s);
// And add to the HashMap put() takes two arguments, "key" and "value"
// The key for us is the String and the value is the Word object
words[s] = w;
if (file == "dracula") {
w.incrementDracula();
} else if (file == "frankenstein") {
w.incrementFranken();
}
}
}
}