about summary refs log blame commit diff stats
path: root/js/bird-words/browser-beak.js
blob: c76f7f68457688e623aea804332f52928a97f8ff (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
















                                                                                                
                   






























                                                                                                                                           
function wrap(str, width) {
    let words = str.split(' ');
    let output = words.reduce((output, word) => {
        if (output.length === 0 || output[output.length - 1].length + word.length + 1 > width) {
            output.push(word);
        } else {
            output[output.length - 1] += ' ' + word;
        }
        return output;
    }, []).join('\n');
    return output;
}

function prettyItUp(string) {
    return string.charAt(0).toUpperCase() + string.slice(1) + "!";
}

fetch('corpus.txt')
    .then(response => response.text())
    .then(data => {
        let corpus = data;
        let words = corpus.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").replace(/\n/g, " ").replace(/\s{2,}/g, " ").split(" ");

        let markovChain = new Map();

        for (let i = 0; i < words.length - 2; i++) {
            let pair = words[i] + ' ' + words[i + 1];
            if (!markovChain.has(pair)) {
                markovChain.set(pair, []);
            }
            markovChain.get(pair).push(words[i + 2]);
        }

        let pairs = Array.from(markovChain.keys());
        let randomPair = pairs[Math.floor(Math.random() * pairs.length)];
        let story = randomPair;
        const storyLength = 100;

        for (let i = 0; i < storyLength; i++) { 
            let nextWords = markovChain.get(randomPair);
            if (!nextWords) {
                break;
            }
            randomPair = randomPair.split(' ')[1] + ' ' + nextWords[Math.floor(Math.random() * nextWords.length)];
            story += ' ' + randomPair.split(' ')[1];
        }

        document.getElementById('beak').innerHTML = prettyItUp(story);
    });