Javascript String fnWordOccurance()

Description

Javascript String fnWordOccurance()


"use strict";//  w  ww . j a va2  s  .c  o  m

function stringOccurance(str) {
 if (typeof str !== 'string') return null;
 return str.match(/([^\s\W]+)/gmi).reduce((newMap, match, index, oldArray) => {
  if (newMap.has(match)) {
   newMap.set(match, newMap.get(match) + 1);
  } else {
   newMap.set(match, 1);
  }
  return newMap;
 }, new Map());
}

String.prototype.fnWordOccurance = function () {
 return stringOccurance(this.toString());
}

Object.defineProperty(String.prototype, "WordOccurance", {
 get: function WordOccurance() {
  return stringOccurance(this.toString());
 }
});

module.exports = {
}



PreviousNext

Related