高阶函数

记录一下这本书的习题的答案,这是第五章的练习。

To the book page

Flattening

将包含数组的数组展开,即只有一对中括号的数组。

1
2
3
4
5
6
7
let arrays = [[1, 2, 3], [4, 5], [6]];
// Your code here.
let combineArrays = arrays.reduce((accumulator,currentArray)=>{
return accumulator.concat(currentArray);
},[])
console.log(combineArrays);
// → [1, 2, 3, 4, 5, 6]

Your own loop

如果不能满足条件(testAct)就不能继续循环。下一次循环要用新的值(updateAct),每次循环需要执行一定的操作(bodyAct)。

1
2
3
4
5
6
7
8
9
10
11
12
// Your code here.

function loop(value, testAct, updateAct,bodyAct){
if(!testAct(value)) return false;
bodyAct(value);
return loop(updateAct(value),testAct,updateAct,bodyAct);
}

loop(3, n => n > 0, n => n - 1, console.log);
// → 3
// → 2
// → 1

Everything

判断数组中所有元素是否都满足一定的条件,和some函数相反。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function every(array, test) {
// Your code here.
for(item of array){
if(!test(item)){
return false;
}
}
return true;
// return !array.some(element=>!test(element));

}

console.log(every([1, 3, 5], n => n < 10));
// → true
console.log(every([2, 4, 16], n => n < 10));
// → false
console.log(every([], n => n < 10));
// → true

Dominant writing direction

找出文字中最主要的读法方向。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function dominantDirection(text) {
// Your code here.
let counted = countBy(text,char =>{
let script = characterScript(char.codePointAt(0));
return script ? script.direction : "none";
}).filter(({name}) => name!="none");
if(counted.length == 0) return "ltr";
return counted.reduce((a,b)=>a.count>b.count?a:b).name;
}

console.log(dominantDirection("Hello!"));
// → ltr
console.log(dominantDirection("Hey, مساء الخير"));
// → rtl

这是countBy,作用是返回数组中满足要求的数量,groupName作为函数名称调用,返回属于当前item所属于的组名称,在这里有两个组别,分别是true组和false组,然后将所在组的数量加1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function countBy(items, groupName) {
let counts = [];
for (let item of items) {
let name = groupName(item);
let known = counts.find(c = c.name == name);
if (!known) {
counts.push({name, count: 1});
} else {
known.count++;
}
}
return counts;
}

console.log(countBy([1, 2, 3, 4, 5], n => n > 2));
// → [{name: false, count: 2}, {name: true, count: 3}]

这是characterScript,作用是判断code属于哪一种语言。

1
2
3
4
5
6
7
8
9
10
11
12
13
function characterScript(code) {
for (let script of SCRIPTS) {
if (script.ranges.some(([from, to]) => {
return code >= from && code < to;
})) {
return script;
}
}
return null;
}

console.log(characterScript(121));
// → {name: "Latin", …}

SCRIPTS类型的格式:

1
2
3
4
5
6
7
8
{
name: "Coptic",
ranges: [[994, 1008], [11392, 11508], [11513, 11520]],
direction: "ltr",
year: -200,
living: false,
link: "https://en.wikipedia.org/wiki/Coptic_alphabet"
}