题目很简单,描述如下:

把数字转化为 lcd 灯的表现形式,打印在控制台上。下面是 0~9 的样子:

1
2
3
._.   ...   ._.   ._.   ...   ._.   ._.   ._.   ._.   ._.
|.| ..| ._| ._| |_| |_. |_. ..| |_| |_|
|_| ..| |_. ._| ..| ._| |_| ..| |_| ..|

例子: 910

1
2
3
._. ... ._.
|_| ..| |.|
..| ..| |_|

测试用例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const main = require("../main/main");

describe("main()", () => {
it("should return 910", () => {
let actual = main("910");
expect(actual).toBe("._. ... ._.\n" + "|_| ..| |.|\n" + "..| ..| |_|\n");
});
it("should return 256", () => {
let actual = main("256");
expect(actual).toBe("._. ._. ._.\n" + "._| |_. |_.\n" + "|_. ._| |_|\n");
});

it("should return 7", () => {
let actual = main("7");
expect(actual).toBe("._.\n" + "..|\n" + "..|\n");
});
});

我的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function main(number) {
let result = "",
arr = [],
line1 = "._. ... ._. ._. ... ._. ._. ._. ._. ._.".split(
" "),
line2 = "|.| ..| ._| ._| |_| |_. |_. ..| |_| |_|".split(
" "),
line3 = "|_| ..| |_. ._| ..| ._| |_| ..| |_| ..|".split(
" ");
arr.push(line1);
arr.push(line2);
arr.push(line3);

for (let i = 0; i < 3; i++) {
number.split("").forEach(element => {
result += `${arr[i][element]} `;
});
result = result.slice(0, result.length - 1) + "\n";
}
return result;
};

看到洋神的优雅代码我真是惊了个呆,瞬间觉得自己写的代码好丑陋:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function main(cs) {
return cs
.split("")
.map(c => lcd[c])
.reduce((x, y) => [x[0] + " " + y[0], x[1] + " " + y[1], x[2] + " " + y[2]])
.map(l => l + "\n")
.join("");
};

const lcd = {
"0": ["._.", "|.|", "|_|"],
"1": ["...", "..|", "..|"],
"2": ["._.", "._|", "|_."],
"3": ["._.", "._|", "._|"],
"4": ["...", "|_|", "..|"],
"5": ["._.", "|_.", "._|"],
"6": ["._.", "|_.", "|_|"],
"7": ["._.", "..|", "..|"],
"8": ["._.", "|_|", "|_|"],
"9": ["._.", "|_|", "..|"]
};