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>
<head>
<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>
</head>
<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>
<head>
<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;
border-radius: 25px;
}
h2, #num, #submit, #result {
font-size: 2em;
}
h1{
margin: 0;
color: #f94711;
}
#num, #submit{
border-radius: 25px;
}
</style>
</head>
<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>
<head>
<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;
}
#submit, #addmore{
font-size: x-large;
height: 70px;
}
#result{
color: green;
font-size: xxx-large;
}
</style>
</head>
<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>
<button id="addmore">Add More Time</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 addmoreButton = document.querySelector('#addmore');
const result = document.getElementById('result');
// Add a click event listener to the addmore button
addmoreButton.addEventListener('click', function() {
// 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
submitButton.addEventListener('click', function() {
// 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>