## Monday, January 30, 2023

### Python workout in JavaScript

In this post, I will convert some python code from the book "Python Workout by Reuven M. Lerner" into JavaScript (you may get a copy of the book from his website). The code used in the book are publicly available on his github page.

Lets get started...

# Task 1: Generate a random integer from 1 to 100.

Ask the user repeatedly to guess the number. Until they guess correctly, tell them to guess higher or lower.

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Random Number Generator | Guess the number...</title>

<!-- ***************** CSS ********************* -->
<style type="text/css">
body{
background-color: #db20d96e;
}

h2, #num, #submit, #result {
font-size: 2em;
}

h1{
margin: 0;
color: #f94711;
}
</style>

<body>

<!-- ***************** HTML ********************* -->
<center>
<h2>Am thinking of a number, what is it?</h2>

<input type="number" name="num" id="num" />
<button id="submit">Submit</button>
<br>
<br>

<label type="text" name="result" id="result" />
</center>

<!-- ***************** JS ********************* -->
<script>

// Funtion to get random number between two nums...
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive
}
// Guessed number is...
let guessed_num = getRandomIntInclusive(1, 100);

// Get form entry and compare to the user's guessed number....
let btn = document.getElementById('submit');

btn.onclick = (e) => {
let guess_num = document.getElementById('num').value;
let result = document.getElementById('result');

console.log(guess_num);

if (guessed_num == guess_num){
// console.log('Correct Guess...');
result.innerHTML = `Correct Guess... The number in my mind was: <h1>\${guessed_num}</h1>`

} else if (guessed_num < guess_num) {
// console.log(`Guessed number is too HIGH; try again...`);
result.innerHTML = `Guessed number is too HIGH; try again...`

} else if (guessed_num > guess_num) {
// console.log(`Guessed number is too LOW; try again...`);
result.innerHTML = `Guessed number is too LOW; try again...`
}

}

// `\${guessed_num}`
</script>

</body>
</html>```

# Task 2: Summing numbers

Define "mySum". Accepts any number of numeric arguments as inputs. Returns the sum of those numbers. If invoked without any arguments, returns 0.

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Summing Numbers in an array....</title>

<!-- ***************** CSS ********************* -->
<style type="text/css">
body{
margin: 50px;
background-color: burlywood;
}

center{
background-color: grey;
border: solid 10px;
}

h2, #num, #submit, #result {
font-size: 2em;
}

h1{
margin: 0;
color: #f94711;
}

#num, #submit{
}
</style>

<body>

<!-- ***************** HTML ********************* -->

<center>
<h2>Enter your list of numbers like this: <i>1, 2, 3, 4, 5</i></h2>

<input type="text" name="num" id="num" />
<button id="submit">Submit</button>
<br>
<br>

<label type="text" name="result" id="result" />
</center>

<!-- ***************** JS ********************* -->

<script type="text/javascript">

// Function to sum array of numbers.... https://www.educative.io/answers/how-to-get-the-sum-of-an-array-in-javascript
function mySum(myarray) {
let sum = 0;

for (let i = 0; i < myarray.length; i += 1) {
sum += (myarray[i] * 1); // multiply by 1 to convert to number: https://www.freecodecamp.org/news/how-to-convert-a-string-to-a-number-in-javascript/
}

return sum;
}

// Get form entries....
let btn = document.getElementById('submit');
let result = document.getElementById('result');

// Perform the magic...
btn.onclick = (e) => {
let list_of_num = document.getElementById('num').value;
// console.log(typeof(list_of_num))

// Replace spaces....
list_of_num = list_of_num.replace(/\s+/g, '');

// Split by ','...
list_of_num = list_of_num.split(',');

// Use the function above to sum the list...
let sum_of_list_of_num = mySum(list_of_num)

// Display result...
if (isNaN(sum_of_list_of_num)){
result.innerHTML = `<h1>Invalid</h1> Your entries most all be numbers.`;
} else {
result.innerHTML = `The Sum of \${list_of_num} is: <h1>\${sum_of_list_of_num}</h1>`;
}

// console.log(`\${list_of_num}`)
// console.log(mySum(sum_of_list_of_num))
}

</script>

</body>
</html>```

# Task 3: Running Time Average

Here we will use javascript to dynamically add the run time input box.

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Running Time Average...</title>

<!-- ------------------------ CSS -------------------------------- -->
<style type="text/css">
#num{
height: 50px;
width: 320px;
font-size: xx-large;
}

font-size: x-large;
height: 70px;
}

#result{
color: green;
font-size: xxx-large;
}

</style>

<body>

<!-- ------------------------ HMTL -------------------------------- -->

<center>
<h1>Enter the time run for the 10km: </h1>

<input type="number" name="num" id="num" class="num" />
<button id="submit">Submit</button>

<br>
<br>

<label type="text" name="result" id="result" />
</center>

<!-- ------------------------ JS -------------------------------- -->

<script type="text/javascript">

// Select the button element
const submitButton = document.querySelector('#submit');

const result = document.getElementById('result');

// Add a click event listener to the addmore button
// Create a new element
const elem0 = document.createElement('center');
const elem1 = document.createElement('input');
const elem2 = document.createElement('br');

// Set the element's content and style
elem1.style.color = 'red';
elem1.style.width = '600px';
elem1.style.height = '50px';
elem1.style.fontSize = 'xx-large';

elem1.type = 'number';

// Add a class and id named 'num' to the element
elem1.className = 'num';
elem1.id = 'num';

// Append the 'input' to the 'center' element
elem0.appendChild(elem1);

// Append the element to the DOM
document.body.appendChild(elem0);

// document.body.appendChild(elem1);
document.body.appendChild(elem2);

});

// ---------------------------------------------

// Add a click event listener to the submit button

// const all_time = document.getElementsByClassName('num');
const all_time = document.querySelectorAll('.num');

const averageTimeRan = Array.from(all_time).reduce((total, elem) => total + parseFloat(elem.value), 0) / all_time.length;

result.innerHTML = `The average of total time ran is: \${averageTimeRan.toFixed(2)}`;

});

</script>

</body>
</html>```

This will be a relatively simple one. To convert number to hexadecimal in JavaScript, '16' will be '0x10'.

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- ------------------- CSS --------------------- -->
<style type="text/css">
center{
background-color: cornflowerblue;
border: 2px solid darkslategrey;
}

#number{
height: 2em;
width: 25em;
border: 0.2em solid cornflowerblue;
font-size: large;
}

#convert {
height: 2em;
border: 0.2em solid cornflowerblue;
font-size: large;
}

#result{
color: darkgreen;
font-size: xx-large;
background-color: chartreuse;
padding: 1px 13px 0px 15px;
}

</style>

<body>

<!-- ------------------- HTML --------------------- -->

<center>

<input type="number" name="number" id="number">
<button id="convert">Convert</button>
<br>
<br>

<label id="result"></label>
</center>

<!-- ------------------- JS --------------------- -->

<script type="text/javascript">

// Select the 'number input' element
const numberInput = document.querySelector('#number');

// Select the 'result label' element
const resultLabel = document.querySelector('#result');

// Select the 'convert button' element
const convertButton = document.querySelector('#convert');

// Add a click event listener to the convert button

let number = parseInt(numberInput.value);
let hexString = '0x' + (number).toString(16);

resultLabel.innerHTML = hexString;

});

</script>

</body>
</html>```

# Task 5: Pig Latin

Pig Latin is a language game or argot in which words in English are altered, usually by adding a fabricated suffix or by moving the onset or initial consonant or consonant cluster of a word to the end of the word and adding a vocalic syllable to create such a suffix.

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pig Latin....</title>

<!-- -------------------- CSS --------------------- -->
<style type="text/css">
body{
background-color: darkgoldenrod;
color: firebrick;
}

center{
margin: 100px;
border: 2px solid black;
}

.resultSuccess{
color: chartreuse;
}

.resultError{
color: darkred;
}
</style>
<body>

<!-- -------------------- HTML --------------------- -->

<center>
<h1>Pig Latin - The children's secret language</h1>

<label>Enter word: </label>
<input type="text" id="word">
<button id="wordbutton">Convert</button>

<h2 id="result1" class="resultSuccess"></h2>
<h2 id="result2" class="resultError"></h2>

</center>

<!-- -------------------- JS --------------------- -->

<script type="text/javascript">

// Select the required HTML elements...
let inputWord = document.querySelector('#word');
let buttonWord = document.querySelector('#wordbutton');
let resultLabel1 = document.querySelector('#result1');
let resultLabel2 = document.querySelector('#result2');

// Add a click event listener to the convert button

// Clear the result labels...
resultLabel1.innerHTML = ''
resultLabel2.innerHTML = ''

// Get input word values and remove both leading and trailing spaces.
let word = inputWord.value.trim()

// Check is word is a phrase...
if (word.match(/\s/)) {

resultLabel2.innerHTML = 'Please enter a single word NOT phrase'

} else{

// Check if the first letter is a vowel...
if ( 'aeiou'.includes(word[0]) ) {
resultLabel1.innerHTML = word.concat('way');
} else{
resultLabel1.innerHTML = word.slice(1, ).concat(word[0], 'ay');
}
}

}); // end of function

</script>

</body>
</html>```

# Task 6: Pig Latin Sentence

The difference between this and the one above is that it is able to handle phrases/sentences.

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pig Latin Sentence....</title>

<!-- -------------------- CSS --------------------- -->
<style type="text/css">
body{
background-color: darkgoldenrod;
color: firebrick;
}

center{
margin: 100px;
border: 2px solid black;
}

.resultSuccess{
color: chartreuse;
}

.resultError{
color: darkred;
}
</style>
<body>

<!-- -------------------- HTML --------------------- -->

<center>
<h1>Pig Latin - The children's secret language</h1>

<label>Enter word: </label>
<input type="text" id="word">
<button id="wordbutton">Convert</button>

<h2 id="result1" class="resultSuccess"></h2>
<h2 id="result2" class="resultError"></h2>

</center>

<!-- -------------------- JS --------------------- -->

<script type="text/javascript">

// Select the required HTML elements...
let inputWord = document.querySelector('#word');
let buttonWord = document.querySelector('#wordbutton');
let resultLabel1 = document.querySelector('#result1');
let resultLabel2 = document.querySelector('#result2');

// Add a click event listener to the convert button

// Clear the result labels...
resultLabel1.innerHTML = ''
resultLabel2.innerHTML = ''

// Get input word values and remove both leading and trailing spaces.
let word = inputWord.value.trim()

// Check is word or is a phrase...
if (word.match(/\s/)) {
// Phrases/Sentences are processed here...

let sentence = word.split(' ')

// Using "for/of" loop...
let sentence_text = "";
for (let word of sentence) {
// Check if the first letter is a vowel...
if ( 'aeiou'.includes(word[0]) ) {
sentence_text += word.concat('way');
sentence_text += ' ';

} else{
sentence_text += word.slice(1, ).concat(word[0], 'ay');
sentence_text += ' ';
}

resultLabel2.innerHTML = sentence_text;

}

// Using "for/in" loop...
// for (let word in sentence) {
// 		...
//   sentence_text += sentence[word];
// }

resultLabel2.innerHTML = `	\${sentence_text}`

} else{

// Check if the first letter is a vowel...
if ( 'aeiou'.includes(word[0]) ) {
resultLabel1.innerHTML = word.concat('way');
} else{
resultLabel1.innerHTML = word.slice(1, ).concat(word[0], 'ay');
}
}

}); // end of function

</script>

</body>
</html>```

# Task 7: Ubbi Dubbi

The rules of 'Ubbi Dubbi' are simpler than those of 'Pig Latin'. In 'Ubbi Dubbi', every vowel (a, e, i, o, or u) is prefaced with 'ub'. See the video below to learn more about 'Ubbi Dubbi'.

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>From English to Ubbi Dubbi....</title>

<!-- -------------------- CSS --------------------- -->
<style type="text/css">
body{
background-color: whitesmoke;
color: firebrick;
}

center{
margin: 100px;
border: 2px solid black;
}

.resultSuccess{
color: chartreuse;
}

.resultError{
color: darkred;
}
</style>
<body>

<!-- -------------------- HTML --------------------- -->

<center>
<h1>Convert from English to Ubbi Dubbi</h1>

<label>Enter Word/Sentence: </label>
<input type="text" id="word">
<button id="wordbutton">Convert</button>

<h2 id="result1" class="resultSuccess"></h2>
<h2 id="result2" class="resultError"></h2>

</center>

<!-- -------------------- JS --------------------- -->

<script type="text/javascript">

// Select the required HTML elements...
let inputWord = document.querySelector('#word');
let buttonWord = document.querySelector('#wordbutton');
let resultLabel1 = document.querySelector('#result1');
let resultLabel2 = document.querySelector('#result2');

// Add a click event listener to the convert button

// Clear the result labels...
resultLabel1.innerHTML = ''
resultLabel2.innerHTML = ''

// Get input word values and remove both leading and trailing spaces.
let word = inputWord.value.trim().toLowerCase()

// Check is word or is a phrase...
if (word.match(/\s/)) {
// Phrases/Sentences are processed here...

let sentence = word.split(' ')

// Using "for/of" loop...
let sentence_text = "";
for (let word of sentence) { // 1st loop

let l_text = "";
for (let l of word){ // 2nd loop

// Check if 'word' contain a vowel letter...
if ( 'aeiou'.includes(l) ) {
l_text += 'ub'+l;
} else{
l_text += l;
}

} // 2nd loop

sentence_text += l_text;
sentence_text += ' ';

resultLabel2.innerHTML = sentence_text;

} // 1st loop

// Using "for/in" loop...
// for (let word in sentence) {
// 		...
//   sentence_text += sentence[word];
// }

// resultLabel2.innerHTML = `	\${sentence_text}`

} else{

let l_text = "";
for (let l of word){

// Check if 'word' contain a vowel letter...
if ( 'aeiou'.includes(l) ) {
l_text += 'ub'+l;
} else{
l_text += l;
}

} // end of loop

resultLabel1.innerHTML = l_text;

} // end of else

}); // end of function

</script>

</body>
</html>```

# Conclusion

We have been able to work through some great python to javascript code exercises, much thanks to the book: 'python workout' by Reuven. I hope you found it useful, personally I found it much easier to learn a new language by solving exercises in a familiar language.