-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdominant_writing_direction.js
47 lines (39 loc) · 1 KB
/
dominant_writing_direction.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
// load dependencies
require('./scripts.js');
const countBy = (items, groupName) => {
let counts = [];
for (let item of items) {
let name = groupName(item);
let known = counts.findIndex((count) => count.name === name);
if (known === -1) {
counts.push({ name, count: 1 });
} else {
counts[known].count++;
}
}
return counts;
};
const characterScript = (code) => {
for (let script of SCRIPTS) {
if (
script.ranges.some(([from, to]) => {
return code >= from && code < to;
})
) {
return script;
}
}
return null;
};
const dominantDirection = (text) => {
const directions = countBy(text, (char) => {
let script = characterScript(char.codePointAt(0));
return script ? script.direction : 'none';
}).filter(({ name }) => name !== 'none');
if (directions.length === 0) return 'none';
return directions.reduce((a, b) => (a.count > b.count ? a : b)).name;
};
console.log(dominantDirection('Hello!'));
// → ltr
console.log(dominantDirection('Hey, مساء الخير'));
// → rtl