Skip to main content
Post Made Community Wiki by 200_success
Source Link

Thanks for all the great and detailed feedback. A lot of great input. I've tried to rewrite the JS based on your different input.

I ditched jQuery, ditched the for loop and much more.

I ditched jQuery and tried to rewrite based on your input. Here is the new version:

document.addEventListener("DOMContentLoaded", function() {
    'use strict';

    function words(text) {
        return text
            .replace(/[-'.]/ig, "") // Ignores hyphens and apostrophes. Dots are here to avoid split on . in numbers.
            .split(/[^a-zA-ZæøåÆØÅ0-9]/g) // Can't use \W+ since I need to take into account danish character ÆØÅ
            .filter(Boolean);
    }

    function sentences(text) {
        var splitter = /\?|\!|\.|\n/g;
        var arrayOfSentences = text
            .split(splitter)
            .filter(Boolean);
        return arrayOfSentences;
    }

    function calculateLix(text) {
        var wordCount = words(text).length;
        var longWordsCount = words(text)
            .filter(function(wordsArray) { return wordsArray.length > 6; })
            .length;
        var sentenceCount = sentences(text).length;
        var lixScore = Math.round((wordCount / sentenceCount) + ((longWordsCount * 100) / wordCount));
        return lixScore;
    }

    document.getElementById('lixButton').addEventListener('click', function() {
        var t0 = performance.now();
        var text = document.getElementById('inputLix').value;
        document.querySelector('#notification').textContent = calculateLix(text).toString();
        var t1 = performance.now();
        console.log('Took', (t1 - t0).toFixed(4), 'milliseconds');
    });
});
.tool-wrapper {
  background: #899398;
  padding: 30px;
  border-radius: 10px;
}

textarea {
  width: 100%;
}
<div class="tool-wrapper">
  <textarea id="inputLix" rows="15">This is just some basic text. Push the button to calculate the LIX value. And figure out how hard your text is to read.</textarea>
  <div class="clearfix">
    <button id="lixButton" class="alignright" type="submit">Calculate Lix</button>
    <div id="notification" class="alignright">You haven't performed any calculations yet</div>
  </div>
</div>