sf-175 / main.js
Blasitoo's picture
Add 2 files
864e708 verified
// Define the application
const App = {
template: `<div class="flex flex-col h-screen">
<header class="p-4">
<h1 class="text-2xl font-bold">Calculator</h1>
<p class="text-gray-500">Use this calculator to perform basic arithmetic operations.</p>
</header>
<main class="px-8">
<div class="flex flex-wrap">
<calculator />
</div>
</main>
</div>`,
data() {
return {
display: 0,
newNum: '',
selectedOperation: '',
previousOperation: '',
result: ''
};
},
methods: {
calculateAndUpdateDisplay() {
if (this.selectedOperation === '') return;
if (this.newNum === '') return;
if (this.previousOperation === '+') {
this.result = this.display + parseInt(this.newNum);
} else if (this.previousOperation === '-') {
this.result = this.display - parseInt(this.newNum);
} else if (this.previousOperation === '*') {
this.result = this.display * parseInt(this.newNum);
} else if (this.previousOperation === '/') {
this.result = this.display / parseInt(this.newNum);
}
this.display = this.result;
this.newNum = '';
},
clearAll() {
this.display = 0;
this.newNum = '';
this.selectedOperation = '';
this.previousOperation = '';
this.result = '';
},
clearNewNum() {
this.newNum = '';
},
addDecimal() {
if (this.newNum === '') return;
this.newNum = `${this.newNum}.`;
}
}
};
// Initialize the calculator component
const calculator = Daisy.component({
template: `<div class="flex flex-col">
<div class="flex flex-wrap">
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="selectedOperation = '1'">1</button>
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="selectedOperation = '2'">2</button>
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="selectedOperation = '3'">3</button>
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="selectedOperation = '/'">/</button>
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="selectedOperation = '*'">*</button>
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="clearAll()">AC</button>
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="clearNewNum()">CE</button>
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="addDecimal()">.</button>
<button class="btn btn-lg bg-gray-300 rounded-lg p-2" x-on:click="calculateAndUpdateDisplay()">=</button>
</div>
</div>`
});