var { percentile } = require('stats-lite');
var categories = /[\p{Mn}\p{Me}]+/u;
var decompose = string => string.normalize('NFD');

/**
 * Determines if the string consists of zalgo text.
 *
 * @param {string} string string
 * @param {number} [threshold=0.55] threshold
 * @return {boolean} boolean
 *
 * @example
 * var snu = require('s-node-utils');
 *
 * snu.is.zalgo('ť͈̓̆h̏̔̐̑ì̭ͯ͞s̈́̄̑͋');
 * //=> true
 */
module.exports = function(string, threshold = 0.55) {
  const wordScores = scores(string);
  const totalScore = percentile(wordScores, 0.75);
  return totalScore >= threshold;
};

function scores(string) {
  const wordScores = [];
  if (!string.trim().length) {
    wordScores.push(0);
  } else {
    for (const word of decompose(string).split(/\s+/)) {
      let banned = 0;
      for (const character of word) {
        if (categories.test(character)) {
          ++banned;
        }
      }
      const score = banned / word.length;
      wordScores.push(score);
    }
  }
  return wordScores;
}
