🧭 計画
JavaScriptのミニ通貨コンバーター(レートキャッシュ+オフラインフォールバック)。
JavaScriptの長さ単位コンバーター(APIなし—係数のみ)。
「ターミナル」で練習するためのPython(CLI)の単一ファイルコンバーター。
UXの小さなこと、テスト、開発のアイデア。
目的:ロジックを理解し、重いフレームワークなしで作業プロトタイプを収集すること。
💱 通貨換算ツール(JavaScript、ブラウザ)
<!-- index.html -->
<div style="max-width:420px;margin:auto;font:16px/1.5 system-ui">
<h2>Конвертер валют</h2>
<label>Сумма: <input id="amount" type="number" step="0.01" value="100"></label><br><br>
<label>Из:
<select id="from">
<option>USD</option><option>EUR</option><option>RUB</option>
</select>
</label>
<label>В:
<select id="to">
<option>EUR</option><option>USD</option><option>RUB</option>
</select>
</label>
<button id="convert">Перевести</button>
<p id="out"></p>
</div>
<script>
const cache = { rates: null, ts: 0 };
// オフライン用のプラグイン:APIが利用できない場合は、架空のレートを使用します
const fallbackRates = { "USD": 1, "EUR": 0.92, "RUB": 92.0 }; // 1 USD = 0.92 EUR, 92 RUB
async function getRates() {
const now = Date.now();
if (cache.rates && (now - cache.ts < 10 * 60 * 1000)) return cache.rates;
try {
// 実際のコースAPIに置き換えてください。重要:CORSと応答フォーマットを確認してください。
// 例:
// const res = await fetch("https://api.example.com/latest?base=USD");
// const data = await res.json(); const rates = data.rates;
// デモでは、次のプラグインを使用します。
const rates = fallbackRates;
cache.rates = rates; cache.ts = now; return rates;
} catch (e) {
console.warn("API is not available, we use a stub", e);
return fallbackRates;
}
}
function formatMoney(value, code) {
// シンプルな書式設定。プロダクションにはIntl.NumberFormatを使用してください
return `${value.toFixed(2)} ${code}`;
}
document.getElementById('convert').addEventListener('click', async () => {
const amount = parseFloat(document.getElementById('amount').value);
const from = document.getElementById('from').value;
const to = document.getElementById('to').value;
const out = document.getElementById('out');
if (Number.isNaN(amount) || amount < 0) {
out.textContent = "Please enter a valid amount (≥ 0).";
return;
}
if (from === to) {
out.textContent = formatMoney(amount, to);
return;
}
const rates = await getRates();
if (!rates[from] || !rates[to]) {
out.textContent = "The selected currency is not supported.";
return;
}
// ベース通貨(USD)に換算し、ターゲット通貨に換算します
const inUSD = amount / rates[from]; // 元の金額の米ドル
const converted = inUSD * rates[to]; // ターゲットに変換します
out.textContent = formatMoney(converted, to);
});
</script>何が起こっているのか: 数値、元の通貨、換算後の通貨を取得し、レートを(APIまたはfallbackRatesから)取得し、USDのベース通貨を介して金額を換算します。 → USD → から.
10分キャッシュ:
cacheは、APIをスパムにしないように、また応答を高速化するために、コースとタイムスタンプを保存します。オフラインモード: ネットワーク/サーバーが利用できない場合は、
fallbackRatesを使用します。デモは常に機能します。検証:
NaNと負の金額を切り捨て、「から=へ」で元の値を表示するだけです。フォーマット: 関数
formatMoneyは2桁に四捨五入します。プロダクションの場合は、ユーザーのロケールにIntl.NumberFormatを取得します。
💡 改善点:input イベントの自動再計算を追加し、localStorage に通貨の選択を保存します。
📏 単位変換(JavaScript、APIなし)
<!-- units.html -->
<div style="max-width:420px;margin:auto;font:16px/1.5 system-ui">
<h2>Конвертер единиц (длина)</h2>
<label>Значение: <input id="val" type="number" step="0.0001" value="1"></label><br><br>
<label>Из:
<select id="uFrom">
<option>m</option><option>cm</option><option>km</option><option>ft</option><option>in</option>
</select>
</label>
<label>В:
<select id="uTo">
<option>cm</option><option>m</option><option>km</option><option>ft</option><option>in</option>
</select>
</label>
<button id="go">Конвертировать</button>
<p id="res"></p>
</div>
<script>
// メートル係数
const length = {
m: 1,
cm: 0.01,
km: 1000,
ft: 0.3048,
in: 0.0254
};
function convert(value, from, to, table) {
if (!(from in table) || !(to in table)) throw new Error("Unit not supported");
const base = value * table[from]; // メートル
return base / table[to]; // ターゲット単位へ
}
document.getElementById('go').addEventListener('click', () => {
const value = parseFloat(document.getElementById('val').value);
const from = document.getElementById('uFrom').value;
const to = document.getElementById('uTo').value;
const res = document.getElementById('res');
if (Number.isNaN(value)) { res.textContent = "Enter a number."; return; }
if (from === to) { res.textContent = `${value} ${to}`; return; }
const out = convert(value, from, to, length);
res.textContent = `${out.toFixed(4)} ${to}`;
});
</script>アイデア: 1つの「基本」単位はメートルです。表では、各単位に「1単位あたりのメートル数」の係数があります。この場合、数式は同じです。 値×係数From →メートル→/係数To.
サポートされている単位の確認: 「静かな」
NaNの代わりに明示的なエラーをスローします。端数処理: エラーを蓄積しないように、最後 (
toFixed(4)) で行います。拡張子: 「質量/体積/速度」カテゴリはまったく同じように機能します。 温度 — 係数ではなく、数式を使用します。
💡単位辞書を units.js に移動し、選択したカテゴリにロードします。
🐍単一ファイルコンバーター(Python、CLI)
# convert.py
from dataclasses import dataclass
RATES = {"USD": 1.0, "EUR": 0.92, "RUB": 92.0} # 必要に応じて実際のものに置き換えてください
UNITS_LEN = {"m":1, "cm":0.01, "km":1000, "ft":0.3048, "in":0.0254}
@dataclass
class Result:
value: float
unit: str
def convert_currency(amount: float, from_code: str, to_code: str) -> Result:
if from_code not in RATES or to_code not in RATES:
raise ValueError("Currency is not supported")
in_usd = amount / RATES[from_code]
out = in_usd * RATES[to_code]
return Result(round(out, 2), to_code)
def convert_length(value: float, from_u: str, to_u: str) -> Result:
if from_u not in UNITS_LEN or to_u not in UNITS_LEN:
raise ValueError("Unit not supported")
base = value * UNITS_LEN[from_u]
out = base / UNITS_LEN[to_u]
return Result(round(out, 4), to_u)
def main():
print("Converter: 1) Currency 2) Length")
mode = input("Select mode (1/2): ").strip()
if mode == "1":
a = float(input("Amount: "))
fc = input("From currency (USD/EUR/RUB): ").strip().upper()
tc = input("In currency (USD/EUR/RUB): ").strip().upper()
res = convert_currency(a, fc, tc)
print(f"→ {res.value} {res.unit}")
elif mode == "2":
v = float(input("Value: "))
fu = input("From (m/cm/km/ft/in): ").strip()
tu = input("In (m/cm/km/ft/in): ").strip()
res = convert_length(v, fu, tu)
print(f"→ {res.value} {res.unit}")
else:
print("Unknown mode")
if __name__ == "__main__":
main()アプローチ: 「純粋な」関数は Result を返し、印刷しないため、テストが簡単です。main() では、入力/出力のみです。
通貨換算: スキームはJSと同じです。USDに変換し、次にターゲット通貨に変換します。四捨五入します 最後にのみ.
長さの変換: メーターに係数の辞書を使用します。数式はすべての単位で同じです。
マネーの精度: 財務上の正確さが必要な場合は、
floatの代わりにdecimal.Decimalを使用してください。
💡変換を別のモジュールに移動し、ユニットテストでカバーします。CLIは細かくします。
UXの小さなことが快適に
イベント
inputの自動再計算(ボタンなし)。localStorageの「から/へ」選択を保存します。結果のコピー:
navigator.clipboard.writeText。通貨の場合、ユーザーのロケールの下に
Intl.NumberFormat。
テストとレーキ
最後に四捨五入します。許容誤差と数値を比較します(epsilon).
温度は係数ではなく数式で表します。
APIを使用する場合は、CORS、制限、更新頻度を確認してください。
B コディケ 私たちはプログラミングの学習を楽しくわかりやすくします。ステップバイステップでスキルを磨くのに役立つ課題を伴う興味深いコースを用意しています。
また、アクティブな テレグラムチャンネル、ここでは素晴らしいアイデアについて話し合い、経験を共有し、課題を一緒に分析します。学習は有益であるだけでなく、楽しいものになります。
