UNPKG

yoastseo-dep

Version:

Yoast clientside page analysis

110 lines (91 loc) 2.92 kB
import { isUndefined, pick } from "lodash-es"; /** * Represents a partial deviation when counting syllables * * @param {Object} options Extra options about how to match this fragment. * @param {string} options.location The location in the word where this deviation can occur. * @param {string} options.word The actual string that should be counted differently. * @param {number} options.syllables The amount of syllables this fragment has. * @param {string[]} [options.notFollowedBy] A list of characters that this fragment shouldn't be followed with. * @param {string[]} [options.alsoFollowedBy] A list of characters that this fragment could be followed with. * * @constructor */ function DeviationFragment( options ) { this._location = options.location; this._fragment = options.word; this._syllables = options.syllables; this._regex = null; this._options = pick( options, [ "notFollowedBy", "alsoFollowedBy" ] ); } /** * Creates a regex that matches this fragment inside a word. * * @returns {void} */ DeviationFragment.prototype.createRegex = function() { let regexString = ""; const options = this._options; let fragment = this._fragment; if ( ! isUndefined( options.notFollowedBy ) ) { fragment += "(?![" + options.notFollowedBy.join( "" ) + "])"; } if ( ! isUndefined( options.alsoFollowedBy ) ) { fragment += "[" + options.alsoFollowedBy.join( "" ) + "]?"; } switch ( this._location ) { case "atBeginning": regexString = "^" + fragment; break; case "atEnd": regexString = fragment + "$"; break; case "atBeginningOrEnd": regexString = "(^" + fragment + ")|(" + fragment + "$)"; break; default: regexString = fragment; break; } this._regex = new RegExp( regexString ); }; /** * Returns the regex that matches this fragment inside a word. * * @returns {RegExp} The regexp that matches this fragment. */ DeviationFragment.prototype.getRegex = function() { if ( null === this._regex ) { this.createRegex(); } return this._regex; }; /** * Returns whether or not this fragment occurs in a word. * * @param {string} word The word to match the fragment in. * @returns {boolean} Whether or not this fragment occurs in a word. */ DeviationFragment.prototype.occursIn = function( word ) { const regex = this.getRegex(); return regex.test( word ); }; /** * Removes this fragment from the given word. * * @param {string} word The word to remove this fragment from. * @returns {string} The modified word. */ DeviationFragment.prototype.removeFrom = function( word ) { // Replace by a space to keep the remaining parts separated. return word.replace( this._fragment, " " ); }; /** * Returns the amount of syllables for this fragment. * * @returns {number} The amount of syllables for this fragment. */ DeviationFragment.prototype.getSyllables = function() { return this._syllables; }; export default DeviationFragment;