Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created February 20, 2018 11:04
Show Gist options
  • Save jonurry/497f1d471286743450e79d7df2fd33d1 to your computer and use it in GitHub Desktop.
Save jonurry/497f1d471286743450e79d7df2fd33d1 to your computer and use it in GitHub Desktop.
5.4 Dominant writing direction (Eloquent JavaScript Solutions)
// 5.4 Dominant Writing Direction
function characterScript(code) {
for (let script of SCRIPTS) {
if (script.ranges.some(([from, to]) => 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 dominantDirection(text) {
let scripts = countBy(text, char => {
let script = characterScript(char.codePointAt(0));
return script ? script.direction : "none";
}).filter(({name}) => name != "none");
switch (scripts.length) {
case 0:
return 'no dominant direction found';
case 1:
return scripts[0].name;
default:
if (scripts.reduce((acc, cur) => acc.count === cur.count)) {
return 'no dominant direction found';
} else {
return scripts.reduce((acc, cur) => acc.count >= cur.count ? acc.name : cur.name);
}
}
}
console.log(dominantDirection("Hello!"));
// → ltr
console.log(dominantDirection("Hey, مساء الخير"));
// → rtl
console.log(dominantDirection(""));
// → no dominant direction found
console.log(dominantDirection("Heyخير"));
// → no dominant direction found
@jonurry
Copy link
Author

jonurry commented Feb 20, 2018

Hints

Your solution might look a lot like the first half of the textScripts example. You again have to count characters by a criterion based on characterScript, and then filter out the part of the result that refers to uninteresting (script-less characters).

Finding the direction with the highest character count can be done with reduce. If it’s not clear how, refer back to the example earlier in the chapter, where reduce was used to find the script with the most characters.

@ibrkhalil
Copy link

just wow <3

@JoseRivera1234
Copy link

This is a brief overview of what you will talk about during the course of your work Due to this the introduction is usually the final part of a paper that students complete for more detail go to the provided link https://www.student-teacher-supervision.org/ In this you can get easy way to advance your essay and it helps in improving your writing skills as well as vocabulary skills.

@henrytirla
Copy link

I found this chapter and example super boring. Your answer helped thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment