我正在学习 Eloquent JavaScript ,但是这个高阶函数练习的答案让我困惑:
function characterScript(code) {
for (let script of SCRIPTS) {
if (script.ranges.some(([from, to]) => {
return code >= from && code < to;
})) {
return script;
}
}
return null;
}
// takes a test function and tells you whether that function
// returns true for any of the elements in the array
function countBy(items, groupName) {
let counts = [];
for (let item of items) {
let name = groupName(item);
let known = counts.findIndex(c => c.name == name);
if (known == -1) {
counts.push({name, count: 1});
} else {
counts[known].count++;
}
}
return counts;
}
// returns an array of objects, each of which names a group
// and tells you the number of elements that were found in that group
function dominantDirection(text) {
let scripts = countBy(text, char => {
let script = characterScript(char.codePointAt(0));
return script ? script.direction : "none";
}).filter(({name}) => name != "none");
if (scripts.length == 0) return "ltr";
return scripts.reduce((a, b) => a.count > b.count ? a : b).name;
}
console.log(dominantDirection("Hello!"));
// → ltr
console.log(dominantDirection("Hey, مساء الخير"));
// → rtl
以下代码返回大数据集中的主要书写方向,该数据集如下所示:
[
{
name: "Coptic",
ranges: [[994, 1008], [11392, 11508], [11513, 11520]],
direction: "ltr",
year: -200,
living: false,
link: "https://en.wikipedia.org/wiki/Coptic_alphabet"
},
// …
]
我理解如何使用 some
方法的循环来查找任何字符代码返回 true
的数组。
但是我无法理解 countBy
函数或 dominantDirection
函数如何导致底部显示的结果。
非常感谢您提供这两个函数的详细说明,以及它们如何导致正确的结果!