Skip to content

Commit 363247a

Browse files
committed
Completed exercise 4.4
1 parent 2b260dc commit 363247a

File tree

2 files changed

+1170
-0
lines changed

2 files changed

+1170
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// load dependencies
2+
require('./scripts.js');
3+
4+
const countBy = (items, groupName) => {
5+
let counts = [];
6+
7+
for (let item of items) {
8+
let name = groupName(item);
9+
let known = counts.findIndex((count) => count.name === name);
10+
if (known === -1) {
11+
counts.push({ name, count: 1 });
12+
} else {
13+
counts[known].count++;
14+
}
15+
}
16+
17+
return counts;
18+
};
19+
20+
const characterScript = (code) => {
21+
for (let script of SCRIPTS) {
22+
if (
23+
script.ranges.some(([from, to]) => {
24+
return code >= from && code < to;
25+
})
26+
) {
27+
return script;
28+
}
29+
}
30+
return null;
31+
};
32+
33+
const dominantDirection = (text) => {
34+
const directions = countBy(text, (char) => {
35+
let script = characterScript(char.codePointAt(0));
36+
return script ? script.direction : 'none';
37+
}).filter(({ name }) => name !== 'none');
38+
39+
if (directions.length === 0) return 'none';
40+
41+
return directions.reduce((a, b) => (a.count > b.count ? a : b)).name;
42+
};
43+
44+
console.log(dominantDirection('Hello!'));
45+
// → ltr
46+
console.log(dominantDirection('Hey, مساء الخير'));
47+
// → rtl

0 commit comments

Comments
 (0)