Last active
July 18, 2025 08:28
-
-
Save tuchida/b07462bd86fc20a6770c2ce048a8e2ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"/> | |
<style> | |
button, | |
.amount, | |
.change { | |
font-size: 2rem; | |
} | |
div { | |
margin: 10px; | |
} | |
.items { | |
display: grid; | |
grid-template-columns: 2fr 1fr; | |
gap: 20px; | |
} | |
.amount { | |
width: 100%; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="items"> | |
</div> | |
<div><span class="expr"></span> = <span class="sum">0</span></div> | |
<div><input class="amount" type="number" value="0" onchange="refresh()"/></div> | |
<div><span class="change">0</span></div> | |
<div><button onclick="reset()">reset</button></div> | |
<script> | |
{ | |
const prices = location.hash.slice(1).split(',').map(Number); | |
const itemsEl = document.querySelector('.items'); | |
for (const p of prices) { | |
const incEl = document.createElement('button'); | |
incEl.textContent = p; | |
incEl.addEventListener('click', () => inc(p)); | |
itemsEl.appendChild(incEl); | |
const decEl = document.createElement('button'); | |
decEl.textContent = `-${p}`; | |
decEl.addEventListener('click', () => dec(p)); | |
itemsEl.appendChild(decEl); | |
} | |
}; | |
const sum = new Map(); | |
const inc = price => { | |
sum.set(price, (sum.get(price) ?? 0) + 1); | |
refresh(); | |
}; | |
const dec = price => { | |
const n = sum.get(price); | |
if (n > 1) { | |
sum.set(price, n - 1); | |
} else { | |
sum.delete(price); | |
} | |
refresh(); | |
}; | |
const refresh = () => { | |
const exprEl = document.querySelector('.expr'); | |
const exprText = [...sum.entries()] | |
.sort(([n], [m]) => n - m) | |
.map(([p, c]) => `${p} * ${c}`) | |
.join(' + '); | |
exprEl.textContent = exprText; | |
const sumEl = document.querySelector('.sum'); | |
let sumValue = 0; | |
for (const [p, c] of sum) { | |
sumValue += p * c; | |
} | |
sumEl.textContent = sumValue; | |
const amountEl = document.querySelector('.amount'); | |
const changeEl = document.querySelector('.change'); | |
changeEl.textContent = (+amountEl.value) - sumValue; | |
}; | |
const reset = () => { | |
sum.clear(); | |
const amountEl = document.querySelector('.amount'); | |
amountEl.value = 0; | |
refresh(); | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment