Building a Javascript calculator with ChatGPT
Asdrúbal Chirinos
Conectando el negocio y el código para el éxito, me especializo en cerrar la brecha entre la visión y la implementación, transformando necesidades en soluciones, y liderando equipos hacia el éxito.
I saw a tweet where someone invited to watch him develop a calculator with Javascript and I wondered? how would chatGPT do it?
My first prompt for chatGPT was: I am planning on creating a functional calculator using only JavaScript, please help me on this.
ChatGPT comes with a generic answer and this code:
// Addition functio
function add(a, b) {
? ? return a + b;
}
// Subtraction function
function subtract(a, b) {
? ? return a - b;
}
// Multiplication function
function multiply(a, b) {
? ? return a * b;
}
// Division function
function divide(a, b) {
? ? if (b == 0) {
? ? ? ? return "Error: Cannot divide by 0.";
? ? }
? ? return a / b;
}n
Duh!
Then I prompted chatGPT again: Create the UI of calculator like buttons with the respective numbers and operation, and when clicked it calls the appropriate function with the required parameters.
ChatGTP now gave me back a HTML, CSS and JS.
HTML
<div class="calculator"
? <div class="display"></div>
? <div class="buttons">
? ? <button class="button operator" value="clear">C</button>
? ? <button class="button operator" value="backspace">CE</button>
? ? <button class="button operator" value="%">%</button>
? ? <button class="button operator" value="/">÷</button>
? ? <button class="button" value="7">7</button>
? ? <button class="button" value="8">8</button>
? ? <button class="button" value="9">9</button>
? ? <button class="button operator" value="*">×</button>
? ? <button class="button" value="4">4</button>
? ? <button class="button" value="5">5</button>
? ? <button class="button" value="6">6</button>
? ? <button class="button operator" value="-">-</button>
? ? <button class="button" value="1">1</button>
? ? <button class="button" value="2">2</button>
? ? <button class="button" value="3">3</button>
? ? <button class="button operator" value="+">+</button>
? ? <button class="button" value="0">0</button>
? ? <button class="button" value=".">.</button>
? ? <button class="button operator" value="=">=</button>
? </div>
</div>
领英推荐
CSS
.calculator
? width: 300px;
? margin: 0 auto;
? background-color: #f1f1f1;
? border-radius: 10px;
? padding: 20px;
}
.display {
? width: 100%;
? height: 80px;
? font-size: 2em;
? background-color: #fff;
? border: none;
? text-align: right;
? padding-right: 20px;
? box-sizing: border-box;
}
.buttons {
? display: flex;
? flex-wrap: wrap;
}
.button {
? width: 25%;
? height: 60px;
? font-size: 1.5em;
? background-color: #fff;
? border: none;
? color: #333;
}
.button:hover {
? background-color: #eee;
}
.operator {
? background-color: #ddd;
}
JS
const buttons = document.querySelectorAll('.button')
buttons.forEach( button => {
? ? button.addEventListener('click', (e) => {
? ? ? ? let value = e.target.value;
? ? ? ? if(value === 'clear') clear() // calls the clear function
? ? ? ? else if(value === 'backspace') backspace() // calls the backspace function
? ? ? ? else if(value === '%') operation('%')?
? ? ? ? else if(value === '*') operation('*')?
? ? ? ? else if(value === '/') operation('/')?
? ? ? ? else if(value === '-') operation('-')?
? ? ? ? else if(value === '+') operation('+')?
? ? ? ? else if(value === '=') operation('=')
? ? ? ? else if(value === '.') addDecimal()
? ? ? ? else if(isNumber(value)) addNumber(value)
? ? })
});
Awesome!, however JS lacks implementations of some functions.
So I prompt chatGPT again: Please help me write the code implement those methods and performs the operations.
ChatGPT answer was impressive. He return me this code with some explanations.
//Global variables to keep track of current number, previous number and operation
let currentNumber = '';
let previousNumber = '';
let operation = undefined;
// function to clear the display
function clear() {
? ? currentNumber = '';
? ? previousNumber = '';
? ? operation = undefined;
}
// function to delete the last digit from current number
function backspace() {
? ? currentNumber = currentNumber.toString().slice(0, -1);
}
// function to add decimal point to current number
function addDecimal() {
? ? if (!currentNumber.includes('.')) {
? ? ? ? currentNumber += '.';
? ? }
}
// function to add number to current number
function addNumber(number) {
? ? currentNumber = currentNumber.toString() + number.toString();
}
// function to perform the mathematical operation
function operate(operator) {
? ? if(operator === '+' || operator === '-' || operator === '*' || operator === '/' || operator === '%') {
? ? ? ? previousNumber = currentNumber;
? ? ? ? currentNumber = '';
? ? ? ? operation = operator;
? ? } else if(operator === '=') {
? ? ? ? currentNumber = eval(previousNumber + operation + currentNumber);
? ? ? ? operation = undefined;
? ? ? ? previousNumber = '';
? ? }
}
const display = document.querySelector('.display')
// update display function
function updateDisplay() {
? ? display.innerHTML = currentNumber;
};
button.addEventListener('click', (e) => {
? ? let value = e.target.value;
? ? if(value === 'clear') clear(); updateDisplay();
? ? else if(value === 'backspace') backspace(); updateDisplay();
? ? else if(value === '%' || value === '+' || value === '-' || value === '*' || value === '/') {
? ? ? ? ? ? operate(value); updateDisplay();
? ? }?
? ? else if(value === '=') {
? ? ? ? operate(value); updateDisplay();
? ? }
? ? else if(value === '.') addDecimal(); updateDisplay();
? ? else if(isNumber(value)) {
? ? ? ? addNumber(value); updateDisplay();
? ? }
})
function isNumber(n) {
? ? return !isNaN(parseFloat(n)) && isFinite(n);
}
Although there were some obvious errors on some code, they were easy to identify and resolve.
Once this was done, I put the pieces together and voila, I had a working calculator!