单元 Converter
你将构建什么
小库 的 conversion 函数 — kilometers 到 miles, Celsius 到 Fahrenheit, and 后面 — plus dispatcher 那个选取正确 conversion 通过 name.
学习目标
- 编写 pure 函数那个映射 one 值到 another
- Use lookup 对象到 dispatch 通过字符串键
- 练习 inverse conversions (round-trip)
- 组织 related 函数到 one 模块
前置要求
- 函数 and 返回值
- 对象 / dictionaries as lookup 表
- 基础 arithmetic and 单元 awareness
步骤
- 1
编写长度 conversions
定义
kmToMiles(km)andmilesToKm(mi). factor 是 1 km ≈ 0.621371 miles. Keeping 每个 conversion in 它的 own 函数制作它们简单到 测试 and reuse.代码function kmToMiles(km) { return km * 0.621371; } function milesToKm(mi) { return mi / 0.621371; }预期结果
kmToMiles(10) 返回关于 6.21371; milesToKm(6.21371) 返回关于 10.
- 2
编写 temperature conversions
定义
celsiusToFahrenheit(c)andfahrenheitToCelsius(f). formulas 是 F = C*9/5 + 32 and C = (F - 32) * 5/9.代码function celsiusToFahrenheit(c) { return c * 9 / 5 + 32; } function fahrenheitToCelsius(f) { return (f - 32) * 5 / 9; }预期结果
celsiusToFahrenheit(0) 返回 32; fahrenheitToCelsius(98.6) 返回关于 37.
- 3
构建 dispatcher
创建对象
converters谁的键 是 conversion names and 谁的值 是函数.convert(name, 值)helper looks 上函数 and calls 它. 这个模式 scales 到许多 conversions 不使用 giant 如果/else.代码const converters = { "km-to-miles": kmToMiles, "miles-to-km": milesToKm, "c-to-f": celsiusToFahrenheit, "f-to-c": fahrenheitToCelsius, }; function convert(name, value) { const fn = converters[name]; if (!fn) return "Unknown conversion"; return fn(value); }预期结果
convert("km-to-miles", 10) 返回 6.21371; convert("c-to-f", 100) 返回 212.
- 4
验证 round-trips
好 conversion 是 invertible: converting 后面应该返回原始值 (在内 rounding). 测试 one 长度 and one temperature round-trip.
代码console.log(milesToKm(kmToMiles(42))); // ≈ 42 console.log(fahrenheitToCelsius(celsiusToFahrenheit(25))); // ≈ 25预期结果
两者都行 print 数字 very 关闭到 42 and 25 respectively.
提示
Floating-点 math 是不 精确 — 小 differences 如 41.99999 是 expected.
- 5
添加输入验证
在主逻辑入口处添加输入验证:检查输入是否为有效数字、是否在允许范围内,对非法输入给出清晰提示而非崩溃。这是健壮程序的第一道防线。
代码function validateInput(value, min, max) { if (typeof value !== "number" || Number.isNaN(value)) { throw new Error(`Invalid input: ${value} is not a number`); } if (value < min || value > max) { throw new Error(`Input ${value} out of range [${min}, ${max}]`); } return value; } // Usage const input = validateInput(rawInput, 1, 100);预期结果
非法输入(非数字或超出范围)会抛出清晰的错误信息,合法输入正常通过。
提示
使用 try/catch 包裹调用处,向用户展示友好的错误提示。
自己动手试试
// TODO: implement kmToMiles, milesToKm, celsiusToFahrenheit, fahrenheitToCelsius
// Then build a `converters` object and a `convert(name, value)` dispatcher.
function convert(name, value) {
// TODO: look up the function in converters and call it
}function kmToMiles(km) { return km * 0.621371; }
function milesToKm(mi) { return mi / 0.621371; }
function celsiusToFahrenheit(c) { return c * 9 / 5 + 32; }
function fahrenheitToCelsius(f) { return (f - 32) * 5 / 9; }
const converters = {
"km-to-miles": kmToMiles,
"miles-to-km": milesToKm,
"c-to-f": celsiusToFahrenheit,
"f-to-c": fahrenheitToCelsius,
};
function convert(name, value) {
const fn = converters[name];
if (!fn) return "Unknown conversion";
return fn(value);
}
console.log(convert("km-to-miles", 10)); // 6.21371
console.log(convert("c-to-f", 100)); // 212你学到了什么
你 composed pure 函数到 小库 and used lookup 对象 as dispatcher — 模式那个 scales 远 better than 长如果/else 链.
相关资源
相关练习
- 函数查找
读取 and tracing 小函数如 这些 converters.
- 数据类型 Predict
Predict 类型 returned 通过 arithmetic 表达式.
相关工具
- Temperature Converter
production tool 那个做 相同 conversions in 浏览器.
- 长度 / 基础 Converter
Another 单元-样式 converter 到 compare 模式使用.
相关速查表
- JavaScript Cheatsheet
函数 and 对象语法引用.
相关参考文档
- JavaScript Math
Arithmetic and 数字 conversion 引用.
相关错误
- 类型错误
操作 on incompatible 类型.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- 类型错误
操作 on incompatible 类型.