Published
Edited
Apr 7, 2021
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
md`all English words: https://stackoverflow.com/questions/34814952/javascript-find-english-word-in-string/34815119`
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
//display3 = html`${replace}`
Insert cell
viewof nextButton = Button(display3, {
reduce: textInput => displayText(textInput)
})
Insert cell
mutable stanzaNumber = 0;
Insert cell
md`To do: split display text into two functions: one for defining every word in displayed stanza, and one for button that becomes functional after defining all words in stanza--pressing button reveals next stanza.`
Insert cell
poem1Stanzas.length
Insert cell
thisStanza = poem1Stanzas[6].split(/[ \n]/);
Insert cell
displayText = function() {
// mutable stanzaNumber ++;
// DEBUGGING console.log("displayText");
//for every stanza
let oldStanza = RiTa.tokenize(poem1Stanzas[stanzaNumber]); //array of words in old stanza
let newStanza = makeNewPoem(poem1Stanzas[stanzaNumber]); //array of words in new stanza
let tokenizedNewStanza = RiTa.tokenize(newStanza);
//ask user to define new displayed gibberish//
/*if (replacementGibberish.length > 0){ //if there are still words to replace
for(let j=0; j>newStanza.length; j++){ //for every word in new stanza
for(let f=0; f>replacementGibberish.length; f++){ //for every Gibberish left to replace
if (tokenizedNewStanza[j].toLowerCase() == replacementGibberish[f]){ //check each word with every word in replacementGibberish //capitals may be a problem
display2.innerText = "‘" + replacementGibberish[f] + "’ means:";
if (textInput !== "") {
let text = textInput;
Dictionary[oldStanza[j].toLowerCase()].userSynonym = text; //search through Dictionary map using real word from oldStanza, which should output an object. Replace the value in key "userSynonym" with the inputted text
replacementGibberish.splice(f); //remove defined gibberish from replacementGibberish
}
}
}
}
//if not replacementGibberish left to define
} else {
display2.innerText = "Done.";
display3.innerText = "Complete Poem";
}*/
if (stanzaNumber < poem1Stanzas.length){
if(poem1Stanzas[stanzaNumber+1] == "\n") {
mutable stanzaNumber += 2;
mutable txt += "<br>" + makeNewPoem(poem1Stanzas[stanzaNumber]) + "<br>";
} else {
mutable stanzaNumber ++;
mutable txt += "<br>" + makeNewPoem(poem1Stanzas[stanzaNumber]); // add new stanza string to mutable text
}
} else {display3.innerText = "Done.";}

//pause a couple second
//button appears on screen with "Write a poem?" on it
//-->pressing the button causes the current display to fade out and me replaced by the new poem appearring word by shifting word on screen
}
Insert cell
function makeNewPoem(poem) {
for(let i = 0; i<replacementWords.length; i++){ //for every word to replace
poem = becomeGibberish(poem.split(/[ \n]/), replacementWords[i], Dictionary[replacementWords[i]].gibberishWord);
}
return poem; //turn poem array into string
}
Insert cell
/*displayText = function() {
// DEBUGGING console.log("displayText");
if (unusedWords[0].length > 0) {
//random index of unusedWords
let index = getRandomInt(0, unusedWords[0].length);
//word to replace chosen from list of unused words
let wordToReplace = unusedWords[0][index];
//generate gibberish based off word to replace
mutable replace = "word replaced: " + wordToReplace;
let gibberish = generateGibberish(wordToReplace);
//Dictionary[wordToReplace] = gibberish;

//adding user input & gibberish to Dictionary object:
if (textInput !== "") {
let text = textInput;
Dictionary.set( wordToReplace, {gibberishWord: gibberish, userSynonym: text});
}

//Supposed to remove highlighting, but not working
mutable txt = txt.replace("<mark>", "");
mutable txt = txt.replace("</mark>", "");

mutable txt = becomeGibberish(
// The following does not treat things like "<" as tokens: --why does tokenize make "<" into tokens but not split?
txt.split(" "),
// RiTa.tokenize(mutableTxt[0]),
wordToReplace,
gibberish
); //word to gibberish
unusedWords[0].splice(index, 1); //removed the replaced word from the list of unused words

display2.innerText = "‘" + gibberish + "’ means:";
} else {
display2.innerText = "Done.";

//pause a couple second
//button appears on screen with "Write a poem?" on it
//-->pressing the button causes the current display to fade out and me replaced by the new poem appearring word by shifting word on screen
}
//}
}*/
Insert cell
/*newPoem = function(replacementWords) {
for(let i=0; i>
//random index of unusedWords
let index = getRandomInt(0, replacementWords[0].length);
//word to replace chosen from list of unused words
let wordToReplace = unusedWords[0][index];
//generate gibberish based off word to replace
let gibberish = generateGibberish(wordToReplace);
//Dictionary[wordToReplace] = gibberish;
//Supposed to remove highlighting, but not working
mutable txt = txt.replace("<mark>", "");
mutable txt = txt.replace("</mark>", "");

mutable txt = becomeGibberish(
// The following does not treat things like "<" as tokens: --why does tokenize make "<" into tokens but not split?
txt.split(" "),
// RiTa.tokenize(mutableTxt[0]),
wordToReplace,
gibberish
); //word to gibberish
replacementWords[0].splice(index, 1); //removed the replaced word from the list of unused words

}
}*/
Insert cell
//document.addEventListener('keydown', displayText);
Insert cell
/*document.addEventListener('keydown', e => {
console.log(`${e.key} pressed`); // for DEBUGGING ONLY
e.stopPropagation();
if (e.key == "Enter") {
e.key = "";
displayText();
}
})*/
Insert cell
/*update = function(lPoem) {
let words = RiTa.tokenize(mutableTxt[0]); // split into words

// loop a random number of times: 1 - numberOfPossibleReplacements
//loop from random spot
let r = Math.floor(Math.random() * words.length);
//for (let i = r; i < words.length + r; i++) {
//let idx = i % words.length;
let idx = r % words.length;
words[idx] = randomWord(lPoem[idx], words[idx]);
//}
return RiTa.untokenize(words);
// mutable txt = RiTa.untokenize(words); // actually even with await Promises ... this does not work
// mutableTxt[0] = RiTa.untokenize(words); // this would also work
}*/
Insert cell
Insert cell
//choosing random word in poem to turn into Gibberish
function becomeGibberish(poem, wordToReplace, gibberish) {
//words = string of poem
for (let ii = 0; ii < poem.length; ii++) {
// bug was ABOVE: ii <= poem.length is wrong:
// array indexes are 0 thru .length-1 but .length *is* the number of elements:
// last index+1 doesn't exist, i.e. is "undefined"
//loop through all elements of words(mutableTxt)
// THIS IS THE FIX for not dealing with word at the end of lines
// (difference fix as compared to the words at beginning problem)
// This still doesn't deal with puntuation [,.?! etc.]
// but you can figure out how to do that ;)
let br = false;
let gibWord = gibberish;
let word = poem[ii];
// looking for "<br>"
let brIndex = word.indexOf("<br>");
if (brIndex != -1) {
word = poem[ii].substr(0, brIndex);
br = true;
}
//remove punctuation
if (word.includes(".")){
gibWord += ".";
word = word.replace(".", "");
}
if (word.includes(",")){
gibWord += ",";
word = word.replace(",", "");
}
if (word.toLowerCase() == wordToReplace) {
//if the element contains the random unused word
if (/[A-Z]/.test(poem[ii][0])) {
word = "<mark>" + RiTa.capitalize(gibWord) + "</mark>"; // keep capitals
} else {
word = "<mark>" + gibWord + "</mark>"; //["<mark>", gibberish, "</mark>"]; //replace the element with gibberish //md`<mark> gibberish </mark>` //supposed to highlight but won't work
}
poem[ii] = word;
if (br) poem[ii] += "<br>";
}
// let newPoem = RiTa.untokenize(poem);
}
return poem.join(" ");
}
Insert cell
md`Test: ${becomeGibberish("very short poem".split(" "), "short", testShort)}`
Insert cell
testShort = generateGibberish("short")
Insert cell
RiTa.tokenize("very short poem")[0].toLowerCase()
Insert cell
Insert cell
//Creating new Gibberish Words based of number of syllabels in input word
function generateGibberish(oWord){
let syllables = RiTa.syllables(oWord);
let syllablesArray = syllables.split('/');
var numSyllables = syllablesArray.length;
var gibberish = "";
var notOneVowel = (oWord.length > 1 && numSyllables == 1);
//stuff about contractions
/*if has Prefix
if ending of prefix = vowel --> start root word with consonant
else --> start root word with vowel
if has suffix
if beginning of suffix = vowel --> end root word with consonant
else --> end root word with vowel
*/

let rand = Math.random();
//What word starts with
if (rand <0.3){
var startVowel = true;
} else {
var startVowel = false;
}
for (let j=0; j<numSyllables; j++){ //loop for number of syllables
//Syllable starts w/ Vowels
if (startVowel == true) {
gibberish += createVowel(notOneVowel);
}
else {
gibberish += createConsonant();
}
if(consonants.indexOf(gibberish.slice(-1)) > 0){
startVowel = true;
}
else{
startVowel = false;
}
}
//if gibberish == real word --> create new gibberish word
return gibberish;
}
Insert cell
//Create a single syllable starting with a vowel:
function createVowel(notOneVowel){
let newVowel = vowels[getRandomInt(0, vowels.length)]; //random starting vowel
let numLetters = getRandomInt(1, 3); //generate random number for either 1 or 2 letter syllable
if (notOneVowel === true){
numLetters = 2;//if one syllable word with more than 1 letter
} //don't allow gibberish to be 1 vowel
if (numLetters > 1){ //if syllable has more than 1 letter
newVowel += consonants[getRandomInt(0, consonants.length)]; //add a random consonant
}
return newVowel;
}
Insert cell
//Create a single syllable starting with a consonant
function createConsonant(){
let newConsonant = consonants[getRandomInt(0, consonants.length)] + vowels[getRandomInt(0, vowels.length)]; //random starting consonant and random addition vowel
let numLetters = getRandomInt(2, 4); // random length 2-3
if(numLetters > 2){ //if syllable 3 letters
newConsonant += consonants[getRandomInt(0, consonants.length)]; //add consonant
}
return newConsonant;
}
Insert cell
function findSuffix(word){
//find suffix from array of prefixes
//group word with other words
//remove syllables from oWord
}
Insert cell
function findPrefix(word){
//find prefix from array of prefixes
//group word with other words
//remove syllables from oWord
}
Insert cell
//This is broken I need to refine the coding later
function findRootWords(poem){
let roots = [];
for(let ii=0; ii<poem.length; ii++){ //for every word in the poem
let rootWord = poem[ii];
let thisPrefix = [];
let thisSuffix = [];
//is there a prefix? --> remove it
for (let jj = 0; jj < prefixes.length; jj++){
if(rootWord.startsWith(prefixes[jj])){
thisPrefix.push(prefixes[jj]);
rootWord = rootWord.replace(prefixes[jj],"");
}
}
//is there a suffix --> remove it
for (let jj = 0; jj < suffixes.length; jj++){
if(rootWord.endsWith(suffixes[jj])){
thisSuffix.push(suffixes[jj]);
rootWord = rootWord.replace(suffixes[jj],"");
}
}
//add to broken down word into a list of objects of root words, prefixes, and suffixes --> when generating gibberish can keep track of letter start and end requirements
roots.push({root: rootWord, prefix: thisPrefix, suffix: thisSuffix});
}
return roots;
}

/*From paragraph that evolves:

if (next.includes(word) || word.includes(next)) {
continue; // skip substrings
}*/
Insert cell
function createPrefixes(prefixList){
let newPrefixList = [];
for(let ii = 0; ii < prefixList.length; ii++){
newPrefixList[ii] = generateGibberish(prefixList[ii]);
}
return newPrefixList;
}
Insert cell
function createSuffixes(suffixList){
let newSuffixList = [];
for(let ii = 0; ii < suffixList.length; ii++){
suffixList[ii] = generateGibberish(suffixList[ii]);
}
return newSuffixList;
}
Insert cell
//Generate an array of all words in an Array[0], with all repeated words removed
function generateUnusedWords(poem){
let words = poem.toLowerCase();
//words = words.split(" ");
words = RiTa.tokenize(words);
//remove punctuation and -g(line break symbol)
let i = 0;
while(i < words.length){
if (words[i] == "." || words[i] == "," || words[i] == "-g"){
words.splice(i, 1);
}
else {
++i;
}
}
return [...new Set(words)];
}
//in future need to alter to account for prefixes and suffixes

/*From paragraph that evolves:

if (next.includes(word) || word.includes(next)) {
continue; // skip substrings
}*/
Insert cell
Insert cell
function generateWordArrays(thePoem){
let fullPoem = [];
let words1 = RiTa.untokenize(thePoem);
let words2 = translatePoem(thePoem, "gibberishWord");
let words3 = translatePoem(thePoem, "userSynonym");
for(let ii = 0; ii < words1.length; ii++){
fullPoem[ii] = Array(words1[ii], words2[ii], words3[ii]);
}
return fullPoem; //output = array of lists of strings
}
Insert cell
function translatePoem(thePoem, toWhat) {
RiTa.tokenize(thePoem[0]);
let newPoem = thePoem;
for (let i=0; i<thePoem.length; i++){
newPoem[i] = Dictionary.get(thePoem[i]).toWhat;
}
return newPoem; //output array of strings
}
Insert cell
function randomWord(wordArray, currentWord) {
// only works with flat arrays of words
let safetyCounter = 0,
word;
do {
word = wordArray[getRandomInt(wordArray.length)];
} while (
currentWord != undefined &&
word == currentWord &&
safetyCounter++ < 100
);
return word;
}
Insert cell
function genDict(replacementWords){
let Dict = new Map();
for (let i=0; i<replacementWords.length; i++){
Dict[replacementWords[i]] = {gibberishWord: generateGibberish(replacementWords[i]), userSynonym: "__"};
}
return Dict;
}
Insert cell
function genRepGib(){
let repGib = [];
for(const key in Dictionary){
repGib.push(Dictionary[key].gibberishWord);
}
return repGib;
}
Insert cell
Insert cell
Insert cell
function gibPoem(oPoem){
let nPoem = oPoem;
for(let ii = 0; ii < oPoem.length; ii++){
if(oPoem[ii] == "-g"){
nPoem[ii] = "-g";
}
else{
nPoem[ii] = generateGibberish(oPoem[ii]);
}
}
return nPoem;
}
Insert cell
Insert cell
Dictionary = genDict(replacementWords);
Insert cell
unmutableTxt = poem1array;
Insert cell
poem1array = ["The glow-pink snow bouncing early sunbeams onto cracked lids. We weep and the tears freeze. Backs to the ground, we carve angels with our eyes clasped shut. Pulse warm palms slow in melting snow. Breathe the early pollen Clumsily, we unfurl, admire our molds. We see the holes our bodies leave and call them angels. Underneath, some cracked seeds unfurl their new tongues. Others freeze, call them clasped palms."];
Insert cell
poem1Stanzas = poem1.innerHTML.split("<br>");
Insert cell
ipi = poem1Stanzas[17] == "\n";
Insert cell
poem1Stanzas[1].split(/[ \n]/)
Insert cell
replacementWords = ["the", "new", "cracked", "we", "and", "freeze", "backs", "carve", "our", "clasped", "palms", "slow", "melting", "breathe", "early", "unfurl", "molds", "bodies", "them", "seeds", "their", "tongues", "others"];
Insert cell
replacementGibberish = genRepGib();
Insert cell
mutable txt2 = poem1.innerHTML
Insert cell
txt2.split(/[ \n]/)
Insert cell
mutable txt = title.innerHTML
Insert cell
title = md`Prayer`
Insert cell
unmutableText = [poem1];
Insert cell
Insert cell
Insert cell
rootWords = [findRootWords(unmutableUnusedWords[0])];
Insert cell
testing2 = findRootWords(["undone", "done", "ouch"]);
Insert cell
testing = generateUnusedWords(unmutableTxt[0]);
Insert cell
display2 = md`Click ‘Gibberfy’` //Text Box Label
Insert cell
display3 = md`Gibberfy` //Button Label
Insert cell
Insert cell
Insert cell
prefixes = ["un", "pre", "in"/*this one may be tough*/, "con"]; //need to add more
Insert cell
suffixes = ["ing", "ish", "less", "ee", "ence", "ful" ]; // also need to add more
Insert cell
gibberishPrefixes = [createPrefixes(prefixes)]
Insert cell
gibberishSuffixes = [createSuffixes(suffixes)];
Insert cell
h = "texting"
Insert cell
function fun(){
let h = "testing";
let e = suffixes[0];
return h.replace(e, "");
}
Insert cell
fun();
Insert cell
function p(){
return suffixes[0];
}
Insert cell
p();
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
import { Button, Text } from "@observablehq/inputs"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more