移植 C++ 账本
Coddy 面向 C++ 开发者的 JavaScript 课程的第 47 课,共 48 课。
挑战
简单将 C++ 参考算法移植到 JavaScript。输入是一个由 [ASCII 名称,整数数量] 对组成的数组。C++ 使用键为字符串、值为 64 位整数总数的有序 std::map;JavaScript 应使用 Map 汇总,并显式排序。仅返回总数为正数的 [名称,总数] 对,并按 ASCII 名称排序。配套的 C++ 程序会运行三个参考测试数据。
C++ 参考程序。完整程序会解析所述 JSON 键值对数组格式,包括转义的 ASCII 名称,并输出 JSON。
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <cstdint>
#include <cctype>
#include <stdexcept>
#include <utility>
// This reader handles the stated array-of-pairs contract with ASCII names.
class Reader {
std::string text;
std::size_t pos=0;
void whitespace() {
while(pos<text.size() && std::isspace(static_cast<unsigned char>(text[pos]))) ++pos;
}
char take() {
if(pos==text.size()) throw std::runtime_error("unexpected end");
return text[pos++];
}
static unsigned hex(char c) {
if(c>='0' && c<='9') return static_cast<unsigned>(c-'0');
if(c>='a' && c<='f') return static_cast<unsigned>(c-'a'+10);
if(c>='A' && c<='F') return static_cast<unsigned>(c-'A'+10);
throw std::runtime_error("bad escape");
}
public:
explicit Reader(std::string input):text(std::move(input)) {}
void token(char expected) {
whitespace();
if(take()!=expected) throw std::runtime_error("bad token");
}
bool next_is(char c) {
whitespace();
return pos<text.size() && text[pos]==c;
}
std::string name() {
token('"');
std::string result;
for(;;) {
unsigned value=static_cast<unsigned char>(take());
if(value=='"') break;
if(value=='\\') {
switch(take()) {
case '"': value='"'; break;
case '\\': value='\\'; break;
case '/': value='/'; break;
case 'b': value='\b'; break;
case 'f': value='\f'; break;
case 'n': value='\n'; break;
case 'r': value='\r'; break;
case 't': value='\t'; break;
case 'u':
value=0;
for(int i=0;i<4;++i) value=value*16+hex(take());
break;
default: throw std::runtime_error("bad escape");
}
}
if(value>127) throw std::runtime_error("non-ASCII name");
result.push_back(static_cast<char>(value));
}
return result;
}
std::int64_t quantity() {
whitespace();
std::size_t consumed=0;
double value=std::stod(text.substr(pos),&consumed);
if(!(value>=-9007199254740991.0 && value<=9007199254740991.0))
throw std::runtime_error("quantity out of bounds");
auto integer=static_cast<std::int64_t>(value);
if(static_cast<double>(integer)!=value) throw std::runtime_error("fractional quantity");
pos+=consumed;
return integer;
}
void finish() {
whitespace();
if(pos!=text.size()) throw std::runtime_error("extra input");
}
};
static void print_name(const std::string& name) {
const char *hex="0123456789abcdef";
std::cout << '"';
for(unsigned char c:name) {
switch(c) {
case '"': std::cout << "\\\""; break;
case '\\': std::cout << "\\\\"; break;
case '\b': std::cout << "\\b"; break;
case '\f': std::cout << "\\f"; break;
case '\n': std::cout << "\\n"; break;
case '\r': std::cout << "\\r"; break;
case '\t': std::cout << "\\t"; break;
default:
if(c<32) std::cout << "\\u00" << hex[c/16] << hex[c%16];
else std::cout << static_cast<char>(c);
}
}
std::cout << '"';
}
int main() {
std::ostringstream input;
input << std::cin.rdbuf();
Reader reader(input.str());
std::map<std::string,std::int64_t> totals;
reader.token('[');
if(!reader.next_is(']')) {
do {
reader.token('[');
auto name=reader.name();
reader.token(',');
auto quantity=reader.quantity();
reader.token(']');
totals[name]+=quantity;
if(!reader.next_is(',')) break;
reader.token(',');
} while(true);
}
reader.token(']');
reader.finish();
std::cout << '[';
bool first=true;
for(const auto& [name,total]:totals) {
if(total<=0) continue;
if(!first) std::cout << ',';
first=false;
std::cout << '[';
print_name(name);
std::cout << ',' << total << ']';
}
std::cout << "]\n";
}
输入是一个 JSON 值。编辑未锁定的文件,从 exercise.js 开始。可见的锁定文件 driver.js 会调用 solve(input),并将返回值作为紧凑 JSON 输出,后跟一个换行符。不要添加诊断输出。测试会比较完整输出。所有数字输入和计算得出的整数总数都在安全整数范围内。
示例输入:
[["pen",3],["book",1],["pen",-1]]预期输出:
[["book",1],["pen",2]]亲手试试
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// 从 stdin 读取一个 JSON 值。返回数据;不要在 solve 中打印。
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
面向 C++ 开发者的 JavaScript中的所有课
自己练习: JavaScript 在线编译器