Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yitonghe00/c34021bebcfaa1f2bbc16dabc85e7f86 to your computer and use it in GitHub Desktop.
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
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