-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path5_4_dominantdirection.js
50 lines (45 loc) · 1.05 KB
/
5_4_dominantdirection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const SCRIPTS = require('./5_scripts');
function characterScript(code) {
for (let script of SCRIPTS) {
if (
script.ranges.some(([from, to]) => {
return code >= from && code < to;
})
) {
return script;
}
}
return null;
}
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;
}
function dominant(counted) {
return counted.reduce((acc, curr) => {
if (acc == null) return curr;
if (curr.count > acc.count) return curr;
return acc;
});
}
function dominantDirection(text) {
return dominant(
countBy(text, char => {
const script = characterScript(char.codePointAt(0));
return script ? script.direction : 'none';
})
).name;
}
console.log(dominantDirection('Hello!'));
// → ltr
console.log(dominantDirection('Hey, مساء الخير'));
// → rtl