Created
April 17, 2020 06:37
-
-
Save yitonghe00/c34021bebcfaa1f2bbc16dabc85e7f86 to your computer and use it in GitHub Desktop.
Eloquent JavaScript 0504 Dominant writing direction.js https://eloquentjavascript.net/05_higher_order.html#i_4ccl4J1nOw
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function dominantDirection(text) { | |
// Your code here. | |
const directions = countBy(text, (char) => { | |
const script = characterScript(char.codePointAt(0)); | |
return script ? script.direction : 'none'; | |
}).filter(({ name }) => name != 'none'); | |
if (directions.length < 2) return directions[0].name; | |
return directions.reduce((a, b) => a.count > b.count ? a.name : b.name); | |
} | |
console.log(dominantDirection("Hello!")); | |
// → ltr | |
console.log(dominantDirection("Hey, مساء الخير")); | |
// → rtl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment