Files
sless/examples/POSTGRES/code/calc-node/handler.js
T

117 lines
5.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Создано: 2026-04-10
// Простой калькулятор — возвращает HTML страницу с кнопками.
// GET → HTML; POST с {a, op, b} → вычисление с результатом на странице.
// Рантайм nodejs20 v0.1.3+ поддерживает HTML-ответ (строка начинающаяся с '<').
'use strict';
const HTML = `<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Калькулятор (Node.js)</title>
<style>
body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #0f2027; }
.calc { background: #1a2a1a; border-radius: 16px; padding: 24px; box-shadow: 0 8px 32px rgba(0,0,0,0.5); width: 280px; }
h2 { color: #d4f7d4; text-align: center; margin: 0 0 16px; font-size: 18px; }
.badge { text-align: center; font-size: 11px; color: #4a7a4a; margin-bottom: 16px; }
.display { background: #0a1a0a; color: #e0ffe0; font-size: 28px; text-align: right; padding: 12px 16px; border-radius: 8px; margin-bottom: 16px; min-height: 52px; word-break: break-all; }
.result { color: #4ade80; font-size: 20px; text-align: right; padding: 4px 16px; margin-bottom: 8px; min-height: 28px; }
.btns { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
button { border: none; border-radius: 8px; padding: 16px 0; font-size: 18px; cursor: pointer; transition: filter 0.1s; }
button:active { filter: brightness(1.3); }
.btn-num { background: #1e3a1e; color: #d4f7d4; }
.btn-op { background: #166534; color: #fff; }
.btn-eq { background: #15803d; color: #fff; grid-column: span 2; }
.btn-clr { background: #7f1d1d; color: #fca5a5; grid-column: span 2; }
.btn-zero { grid-column: span 2; }
</style>
</head>
<body>
<div class="calc">
<h2>Калькулятор</h2>
<div class="badge">Node.js 20</div>
<div id="display" class="display">0</div>
<div id="result" class="result">RESULT_LINE</div>
<div class="btns">
<button class="btn-clr btn-zero" onclick="clr()">C</button>
<button class="btn-op" onclick="setOp('%2F')">÷</button>
<button class="btn-op" onclick="setOp('*')">×</button>
<button class="btn-num" onclick="inp('7')">7</button>
<button class="btn-num" onclick="inp('8')">8</button>
<button class="btn-num" onclick="inp('9')">9</button>
<button class="btn-op" onclick="setOp('-')"></button>
<button class="btn-num" onclick="inp('4')">4</button>
<button class="btn-num" onclick="inp('5')">5</button>
<button class="btn-num" onclick="inp('6')">6</button>
<button class="btn-op" onclick="setOp('+')">+</button>
<button class="btn-num" onclick="inp('1')">1</button>
<button class="btn-num" onclick="inp('2')">2</button>
<button class="btn-num" onclick="inp('3')">3</button>
<button class="btn-num btn-zero" onclick="inp('0')">0</button>
<button class="btn-num" onclick="inp('.')">.</button>
<button class="btn-eq" onclick="calc()">=</button>
</div>
</div>
<script>
let a = '', op = '', b = '';
const disp = document.getElementById('display');
function inp(v) {
if (op === '') { a += v; disp.textContent = a || '0'; }
else { b += v; disp.textContent = b || '0'; }
}
function setOp(o) {
if (a === '') return;
if (b !== '') calc();
else { op = o; disp.textContent = a + ' ' + decodeURIComponent(o) + ' …'; }
}
function clr() { a = ''; op = ''; b = ''; disp.textContent = '0'; }
function calc() {
if (a === '' || op === '' || b === '') return;
const form = document.createElement('form');
form.method = 'POST'; form.action = '';
const fields = {a, op, b};
for (const [k, v] of Object.entries(fields)) {
const i = document.createElement('input');
i.type = 'hidden'; i.name = k; i.value = decodeURIComponent(v);
form.appendChild(i);
}
document.body.appendChild(form);
form.submit();
}
</script>
</body>
</html>`;
// Форматирует число — убирает лишний .0 для целых
function fmt(n) { return n === Math.trunc(n) ? String(Math.trunc(n)) : String(n); }
function buildPage(resultLine) {
return HTML.replace('RESULT_LINE', resultLine || '');
}
function compute(event) {
// POST: тело приходит как JSON; поля a, op, b — строки из form
const a = parseFloat(event.a);
const b = parseFloat(event.b);
const op = event.op;
if (isNaN(a) || isNaN(b)) return buildPage('Некорректное число');
let res;
switch (op) {
case '+': res = a + b; break;
case '-': res = a - b; break;
case '*': res = a * b; break;
case '/':
if (b === 0) return buildPage('Деление на ноль');
res = a / b; break;
default: return buildPage('Неизвестный оператор');
}
return buildPage(`${fmt(a)} ${op} ${fmt(b)} = ${fmt(res)}`);
}
module.exports.handler = async function handler(event) {
if (event._method === 'POST') return compute(event);
return buildPage('');
};