Creating a basic calculator using 2 prompts

I asked Codex to create a calculator using the following prompt:

Create a calculator that can add, subtract, multiply and divide 2 numbers together

/* Create a calculator that can add, subtract, multiply and divide 2 numbers together */
var calculator = document.createElement('div');
calculator.innerHTML = '<input type="text" id="num1" value="0" /> <input type="text" id="num2" value="0" /> <button id="add">+</button> <button id="subtract">-</button> <button id="multiply">*</button> <button id="divide">/</button> <div id="result"></div>';
document.body.appendChild(calculator);
var num1 = document.getElementById('num1');
var num2 = document.getElementById('num2');
var result = document.getElementById('result');
document.getElementById('add').addEventListener('click', function() {
  result.innerHTML = parseInt(num1.value) + parseInt(num2.value);
});
document.getElementById('subtract').addEventListener('click', function() {
  result.innerHTML = parseInt(num1.value) - parseInt(num2.value);
});
document.getElementById('multiply').addEventListener('click', function() {
  result.innerHTML = parseInt(num1.value) * parseInt(num2.value);
});
document.getElementById('divide').addEventListener('click', function() {
  result.innerHTML = parseInt(num1.value) / parseInt(num2.value);
});
I then noticed I needed to add a button to clear the results so I could do another calculation. 

/* create a button that clears the results of the calculator */
var clear = document.createElement('button');
clear.innerHTML = 'Clear';
document.body.appendChild(clear);
clear.addEventListener('click', function() {
  result.innerHTML = '';
});

This thing is so incredibly powerful.

3 Likes

I’ll bet there are a lot of examples of this exact exercise in the training data. So amazing that it has glued all of them together, and it works (almost) perfectly!

1 Like