Write a small program using OOP? Interview

Joined
Feb 16, 2024
Messages
17
Reaction score
0
Hello,

I am wondering what you could possibly answer to the question in the title?

Personally I like my little calculator but it's not OOP (but some people says everything is OOP in JS)

********************************************************************

const operator = prompt('Enter operator ( either +, -, * or / ): ');


const number1 = parseFloat(prompt("Enter first number:"));
const number2 = parseFloat(prompt("Enter second number:"));


let result;

if (operator == '+') {
result = number1 + number2;
}
else if (operator == '-') {
result = number1 - number2;
}
else if (operator == '*') {
result = number1 * number2;
}
else {
result = number1 / number2;
}



console.log(result);

********************************************************************

And you what small program (30 lines max) would you write for such a question? Something practical.

No HTML/No CSS
 
Joined
Jul 4, 2023
Messages
507
Reaction score
63
My interpretation. :cool:
JavaScript:
class Calculator {
  #PROMPT_MESSAGE = `
    Please enter a mathematical expression.
    [ Allowed chars: + - / * ^ % ( ) 0-9 or write: exit ].
  `;

  constructor() {  
    this.expression = '';
  }

  getExpression() {
    const VALIDATION_REGEX = /^[+\-*/\(\)^0-9% ]+$/;
    while (true) {
      // second argument in PROMPT method for presentation purpose only
      this.expression = (prompt(this.#PROMPT_MESSAGE + '\n' + this.expression, '3 + 5 * ((2 - 8) / 2)^2 - 5%')).trim();
      if (VALIDATION_REGEX.test(this.expression) || this.expression.toLowerCase() === 'exit') {
        console.log(`The input is valid: ${this.expression}`); // for presentation purpose
        break;
      } else {
        this.expression = `\tThe input contains invalid characters: ${this.expression}`;
        console.log(this.expression); // for presentation purpose
      }
    }
  }
 
  #transformExpression() {
    this.expression = this.expression.replace(/(\d+(\.\d+)?)%/g, '($1 / 100)'); // x% to (x / 100)
    this.expression = this.expression.replace(/\^/g, '**');
  }

  calculate() {
    if (this.expression.toLowerCase() !== 'exit') {
      let calculation = `Calculate: ${this.expression}\n`;
      this.#transformExpression();
      calculation += `Result: ${eval(this.expression)}`;
      alert(calculation);
      console.log(calculation); // for presentation purpose
    }
  }
}

const calculator = new Calculator();
calculator.getExpression();
calculator.calculate();
 
Last edited:
Joined
Feb 16, 2024
Messages
17
Reaction score
0
Phew, it is a really robust code, but it is also very concrete. I ran it in the compiler, and it work very well.

Why does the application display twice the output?


1718529158162.png



I also see that template strings are being used, and while I am familiar with the concept, I am unable to use it yet, too advanced for the rookie I am.

Would u have an easier example still with OOP?


I am looking for an example to dissect at beginner level to get the hang of it. I quickly get overwhelmed by advanced piece of code.
 
Joined
Jul 4, 2023
Messages
507
Reaction score
63
Would u have an easier example still with OOP?
What about this one, still too advanced?
[ working code on-line ]
JavaScript:
class TodoList {
  #tasks;
  constructor() {
    this.#tasks = [];
  }

  addTask(description) {
    this.#tasks.push(description);
  }

  deleteTask(index) {
    if (index > 0 && index <= this.#tasks.length) {
      this.#tasks.splice(index - 1, 1);
    } else {
      alert("Invalid task index.");
    }
  }

  showTasks() {
    if (this.#tasks.length === 0) {
      alert("No tasks in the list.");
    } else {
      let tasksString = this.#tasks.map((task, index) => `${index + 1}. ${task}`).join('\n');
      return tasksString;
    }
  }
}

const todoList = new TodoList();

function mainMenu() {
  let option, list;
  do {
      option = prompt("Choose an option:\n1. Add task\n2. Delete task\n3. Show all tasks\n4. Exit");
      switch (option) {
          case '1':
              const description = prompt("Enter the task description:");
              todoList.addTask(description);
              break;
          case '2':
              list = todoList.showTasks();
              if (list) {
                const index = parseInt(prompt(list + "\n\nEnter the index of the task to delete:"));
                todoList.deleteTask(index);
              }             
              break;
          case '3':
              list = todoList.showTasks();
              if (list) alert(list);
              break;
          case '4':
              alert("Exiting the program.");
              break;
          default:
              alert("Invalid option, please try again.");
      }
  } while (option !== '4');
}

mainMenu();
 
Joined
Feb 16, 2024
Messages
17
Reaction score
0
What about this one, still too advanced?
[ working code on-line ]
JavaScript:
class TodoList {
  #tasks;
  constructor() {
    this.#tasks = [];
  }

  addTask(description) {
    this.#tasks.push(description);
  }

  deleteTask(index) {
    if (index > 0 && index <= this.#tasks.length) {
      this.#tasks.splice(index - 1, 1);
    } else {
      alert("Invalid task index.");
    }
  }

  showTasks() {
    if (this.#tasks.length === 0) {
      alert("No tasks in the list.");
    } else {
      let tasksString = this.#tasks.map((task, index) => `${index + 1}. ${task}`).join('\n');
      return tasksString;
    }
  }
}

const todoList = new TodoList();

function mainMenu() {
  let option, list;
  do {
      option = prompt("Choose an option:\n1. Add task\n2. Delete task\n3. Show all tasks\n4. Exit");
      switch (option) {
          case '1':
              const description = prompt("Enter the task description:");
              todoList.addTask(description);
              break;
          case '2':
              list = todoList.showTasks();
              if (list) {
                const index = parseInt(prompt(list + "\n\nEnter the index of the task to delete:"));
                todoList.deleteTask(index);
              }            
              break;
          case '3':
              list = todoList.showTasks();
              if (list) alert(list);
              break;
          case '4':
              alert("Exiting the program.");
              break;
          default:
              alert("Invalid option, please try again.");
      }
  } while (option !== '4');
}

mainMenu();

I find it awesome.

I understand the concept of push, break, switch, but I would not be able to build something as sophisticated as that , but at least it helps me to visualize better. What about that example?

const questions = [
{ question: "Which of these can you NOT recycle? \nA - Glass\nB - Paper\nC - Pens and pencils", answer: 'C' },
{ question: "Which colour bin does paper and cardboard go in? \nA - Blue\nB - Green\nC - Yellow", answer: 'A' },
{ question: "Which type of transport is best for the environment? \nA - Bus\nB - Car\nC - Bike", answer: 'C' },
{ question: "What is deforestation? \nA - The loss of trees\nB - The loss of clouds\nC - The loss of water", answer: 'A' },
{ question: "Which of these is a type of green energy? \nA - Petrol\nB - Wind\nC - Wood", answer: 'B' },
{ question: "When you go to the shop, it's best to... \nA - Buy a paper bag\nB - Buy a plastic bag\nC - Bring your re-usable bag from home", answer: 'C' },
];

function quiz() {
let score = 0;

questions.forEach((question) => {
let answer = prompt(question.question + "\nAnswer: ");

if (answer.toUpperCase() === question.answer) {
score += 1;
alert("Your answer is correct. Your score is currently " + score);
} else {
// score -= 1;
alert("Your answer is not correct");
}
});
if (score >= 3) {
alert("You have passed " + score);
} else {
alert("You did not pass " + score)
}
}
quiz();

That one is more manageable for me, but two things I don't get:

questions.forEach((question) => {
let answer = prompt(question.question + "\nAnswer: ");

forEach means that it will apply to every question. but where that question.question is coming from?

I would expect at least questions.question but question.question. Also that little =>..

if (answer.toUpperCase() === question.answer)

UpperCase turns a string to uppercase letters, which is OK, however I do not understand what it accomplishes here. Does it recognize any answer as correct regardless uppercase/lowercase?

What would be your thoughts on that?
 
Joined
Jul 4, 2023
Messages
507
Reaction score
63
forEach means that it will apply to every question. but where that question.question is coming from?
;)
JavaScript:
const questions = [
  { question: "Which of these can you NOT recycle? \nA - Glass\nB - Paper\nC - Pens and pencils", answer: 'C' },
  { question: "Which colour bin does paper and cardboard go in? \nA - Blue\nB - Green\nC - Yellow", answer: 'A' },
  { question: "Which type of transport is best for the environment? \nA - Bus\nB - Car\nC - Bike", answer: 'C' },
  { question: "What is deforestation? \nA - The loss of trees\nB - The loss of clouds\nC - The loss of water", answer: 'A' },
  { question: "Which of these is a type of green energy? \nA - Petrol\nB - Wind\nC - Wood", answer: 'B' },
  { question: "When you go to the shop, it's best to... \nA - Buy a paper bag\nB - Buy a plastic bag\nC - Bring your re-usable bag from home", answer: 'C' },
];

questions.forEach((temporar_variable_for_iteration_of_each_row) => {
  let answer = prompt(temporar_variable_for_iteration_of_each_row.question + "\nAnswer: ");
});

JavaScript:
const questions = [
  { question: "Which of these can you NOT recycle? \nA - Glass\nB - Paper\nC - Pens and pencils", answer: 'C' },
  { question: "Which colour bin does paper and cardboard go in? \nA - Blue\nB - Green\nC - Yellow", answer: 'A' },
  { question: "Which type of transport is best for the environment? \nA - Bus\nB - Car\nC - Bike", answer: 'C' },
  { question: "What is deforestation? \nA - The loss of trees\nB - The loss of clouds\nC - The loss of water", answer: 'A' },
  { question: "Which of these is a type of green energy? \nA - Petrol\nB - Wind\nC - Wood", answer: 'B' },
  { question: "When you go to the shop, it's best to... \nA - Buy a paper bag\nB - Buy a plastic bag\nC - Bring your re-usable bag from home", answer: 'C' },
];

questions.forEach((row, index) => {
  let answer = prompt((index + 1) + ". " + row.question + "\nAnswer: ");
});


JavaScript:
const questions = [
  { question: "Which of these can you NOT recycle? \nA - Glass\nB - Paper\nC - Pens and pencils", answer: 'C' },
  { question: "Which colour bin does paper and cardboard go in? \nA - Blue\nB - Green\nC - Yellow", answer: 'A' },
  { question: "Which type of transport is best for the environment? \nA - Bus\nB - Car\nC - Bike", answer: 'C' },
  { question: "What is deforestation? \nA - The loss of trees\nB - The loss of clouds\nC - The loss of water", answer: 'A' },
  { question: "Which of these is a type of green energy? \nA - Petrol\nB - Wind\nC - Wood", answer: 'B' },
  { question: "When you go to the shop, it's best to... \nA - Buy a paper bag\nB - Buy a plastic bag\nC - Bring your re-usable bag from home", answer: 'C' },
];

let answer = '';
for (const row of questions)
  answer = prompt(row.question + "\nAnswer: ");

JavaScript:
const questions = [
  { question: "Which of these can you NOT recycle? \nA - Glass\nB - Paper\nC - Pens and pencils", answer: 'C' },   // index 0
  { question: "Which colour bin does paper and cardboard go in? \nA - Blue\nB - Green\nC - Yellow", answer: 'A' }, // index 1
  { question: "Which type of transport is best for the environment? \nA - Bus\nB - Car\nC - Bike", answer: 'C' },  // index 2
  { question: "What is deforestation? \nA - The loss of trees\nB - The loss of clouds\nC - The loss of water", answer: 'A' }, // index 3 ...
  { question: "Which of these is a type of green energy? \nA - Petrol\nB - Wind\nC - Wood", answer: 'B' },
  { question: "When you go to the shop, it's best to... \nA - Buy a paper bag\nB - Buy a plastic bag\nC - Bring your re-usable bag from home", answer: 'C' },
];

let answer = '';
for (const index in questions)
  answer = prompt(questions[index].question + "\nAnswer: ");

for (const index in questions)
  answer = prompt(`${(index * 1 + 1)}. ${questions[index].question}\nAnswer:`);
 
Last edited:
Joined
Jul 4, 2023
Messages
507
Reaction score
63
Also that little =>..
Arrow function [ 1 ] [ 2 ]

Before Arrow function
JavaScript:
const questions = [
  { question: "Which of these can you NOT recycle? \nA - Glass\nB - Paper\nC - Pens and pencils", answer: 'C' },
  { question: "Which colour bin does paper and cardboard go in? \nA - Blue\nB - Green\nC - Yellow", answer: 'A' },
  { question: "Which type of transport is best for the environment? \nA - Bus\nB - Car\nC - Bike", answer: 'C' },
  { question: "What is deforestation? \nA - The loss of trees\nB - The loss of clouds\nC - The loss of water", answer: 'A' },
  { question: "Which of these is a type of green energy? \nA - Petrol\nB - Wind\nC - Wood", answer: 'B' },
  { question: "When you go to the shop, it's best to... \nA - Buy a paper bag\nB - Buy a plastic bag\nC - Bring your re-usable bag from home", answer: 'C' },
];

questions.forEach(function(temporar_variable_for_iteration_of_each_row) {
  let answer = prompt(temporar_variable_for_iteration_of_each_row.question + "\nAnswer: ");
});
 
Joined
Jul 4, 2023
Messages
507
Reaction score
63
UpperCase turns a string to uppercase letters, which is OK, however I do not understand what it accomplishes here. Does it recognize any answer as correct regardless uppercase/lowercase?
Comparing characters in javascript are case sensitive.
JavaScript:
alert(`
  'a' == 'a'  -> ${'a' == 'a'}
  'a' == 'A'  -> ${'a' == 'A'}
  'a' === 'a' -> ${'a' === 'a'}
  'a' === 'A' -> ${'a' === 'A'}
`);

JavaScript:
const questions = [
  { ..., answer: 'C' },
  { ..., answer: 'A' },
  { ..., answer: 'C' },
  { ..., answer: 'A' },
  { ..., answer: 'B' },
  { ..., answer: 'C' },
];
In array 'questions' the 'answer' are marks as uppercase, but when you press e.g. button 'a' on your keyboard the letter 'a' is returned as lowercase. You need to press the 'shift' or 'caps lock' in the same time for letter 'a' as uppercase.
 
Last edited:
Joined
Feb 16, 2024
Messages
17
Reaction score
0
Comparing characters in javascript are case sensitive.
JavaScript:
alert(`
  'a' == 'a'  -> ${'a' == 'a'}
  'a' == 'A'  -> ${'a' == 'A'}
  'a' === 'a' -> ${'a' === 'a'}
  'a' === 'A' -> ${'a' === 'A'}
`);

JavaScript:
const questions = [
  { ..., answer: 'C' },
  { ..., answer: 'A' },
  { ..., answer: 'C' },
  { ..., answer: 'A' },
  { ..., answer: 'B' },
  { ..., answer: 'C' },
];
In array 'questions' the 'answer' are marks as uppercase, but when you press e.g. button 'a' on your keyboard the letter 'a' is returned as lowercase. You need to press the 'shift' or 'caps lock' in the same time for letter 'a' as uppercase.

Understood ;)

Where that question.question is coming from?
 
Joined
Jul 4, 2023
Messages
507
Reaction score
63
Comparing characters in javascript are case sensitive.
With this knowledge, and for the user's comfort (the user does not have to take care of the letter case) and to avoid incorrectly inserting a letter (whether an uppercase or lowercase letter) into the array, the proposed comparison notation in the code should look like this (in this particular case, the letter case does not matter), so let's treat both of them as lowercase letters.
JavaScript:
const questions = [
  { ..., answer: 'C' }, // index 0
  { ..., answer: 'a' }, // index 1
  { ..., answer: 'C' }, // index 2
  { ..., answer: 'A' }, // index 3
  { ..., answer: 'b' }, // index 4
  { ..., answer: 'C' }, // index 5
];

if (answer.toLowerCase() === row.answer.toLowerCase()) // treat both of them as lowercase letters


JavaScript:
const questions = [
  { question: "Which of these can you NOT recycle? \nA - Glass\nB - Paper\nC - Pens and pencils", answer: 'C' },
  { question: "Which colour bin does paper and cardboard go in? \nA - Blue\nB - Green\nC - Yellow", answer: 'a' },
  { question: "Which type of transport is best for the environment? \nA - Bus\nB - Car\nC - Bike", answer: 'C' },
  { question: "What is deforestation? \nA - The loss of trees\nB - The loss of clouds\nC - The loss of water", answer: 'A' },
  { question: "Which of these is a type of green energy? \nA - Petrol\nB - Wind\nC - Wood", answer: 'b' },
  { question: "When you go to the shop, it's best to... \nA - Buy a paper bag\nB - Buy a plastic bag\nC - Bring your re-usable bag from home", answer: 'C' },
];

questions.forEach((row, index) => {
  let answer = (prompt((index + 1) + ". " + row.question + "\nAnswer: ") ?? 'Cancel was pressed').trim();
  if (answer.toLowerCase() === row.answer.toLowerCase())
    alert(`Congratulations!\n${answer.toUpperCase()} is correct answer`);
  else
    alert(`Keep trying!\n${(answer === '') ? 'EMPTY' : answer.toUpperCase()} is an invalid answer`);
});
1718703864648.png

1718704374831.png

1718704600488.png
 
Last edited:
Joined
Aug 22, 2023
Messages
59
Reaction score
14
To successfully create an intricate calculator, you should assign numerous constants, and manipulate them with functions, rather than just 4 functions for operators. I suggest assigning more values. You should also not log the result to the console, but rather create another function to change the InnerText of a Document Object, so users can actually view it!:)
JavaScript:
<script>
var get = document.getElementById("lorem");
get.innerText = result;
</script>
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,056
Messages
2,570,443
Members
47,089
Latest member
Bobby2025b

Latest Threads

Top