Skip to content

Instantly share code, notes, and snippets.

@ebachter
Last active November 2, 2016 15:54
Show Gist options
  • Save ebachter/a3410b77fc93da3cbe32b34ccb39bb06 to your computer and use it in GitHub Desktop.
Save ebachter/a3410b77fc93da3cbe32b34ccb39bb06 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Solution</title>
</head>
<body>
<article></article>
<section id="result">
<ol></ol>
</section>
<script>
const parseFile = (() => {
let resultList;
const removeTags = (textWithTags) => textWithTags.replace(/<(?:.|\n)*?>/gm, '');
const getWords = (textWithoutTags) => textWithoutTags.match(/\b[^\d\W]+\b/g);
const countWords = (arrayOfWords) => arrayOfWords.reduce((o, value) => {
!o[value] ? o[value]=1 : o[value] = o[value] + 1;
return o;
}, []);
const makeSortableArray = (objectOfCountedWords)=> Object.keys(objectOfCountedWords).map((k) => ({ word:k, counter: objectOfCountedWords[k] }) );
const sortArray = (sortableArray)=> sortableArray.sort((a, b) => a.counter < b.counter ? 1 : -1);
return {
parseList: function (textWithTags) {
const lowerCaseTextWithoutTags = removeTags(textWithTags).toLowerCase();
const arrayOfWords = getWords(lowerCaseTextWithoutTags);
const objectOfCountedWords = countWords(arrayOfWords);
const sortableArray = makeSortableArray(objectOfCountedWords);
const sortedArray = sortArray(sortableArray);
resultList = sortedArray.map((o) => `<li>${o.word} (${o.counter})</li>`).join('');
},
getFileData: function(path){
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.responseXML);
}
xhr.open("GET", path);
xhr.responseType = "document";
xhr.send();
});
},
getList: function(){
return resultList;
},
}
})();
parseFile.getFileData("index.html")
.then(function(doc) {
const textWithTags = doc.body.getElementsByTagName("article")[0].innerHTML;
document.body.getElementsByTagName("article")[0].innerHTML = textWithTags;
parseFile.parseList(textWithTags);
document.querySelector("#result ol").innerHTML = parseFile.getList();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment