DEV Community


Posted on

Poem generation in JS

I recently came across this awesome site
It generates posts based on the King James Bible, Structure and Interpretation of Computer Programs, and some of Eric S. Raymond's writings.

I wanted to build something similar in JS. So I took Shakespeare sonnets and created this array

const poems = [

I looped through this array and for each word in the array I noted down the subsequent words that comes after. I did this for all sonnets and created an object and wrote this object to a JSON file

{ "From": 
   ["fairest", "his", "sullen", "limits", "hands",
    "whence", "where", "me", "this", "thy",
    "hence", "thee", "you", "heaven"
   "fairest: [...]

And now to generate poem in the UI.

  1. I fetched the JSON picked and then picked random key (this is staring word for the poem)
  2. For that word pick value (value is an array) from JSON
  3. Pick one word from that array of words randomly
  4. Now repeat from step 2 for this word

We can keep doing this till we either reach no further path or till we have number of words we need. And there you have it your own poem generator. Here is link to demo and here is the link to the repo

The best part is you can use it for any text to generate essays, svgs...

Even though we just implemented things like ngram and markov chain in the above code I did not explain it in detail to keep it simple. Here are resources for those who are interested in it.

Top comments (0)