Skip to content

Instantly share code, notes, and snippets.

@truseed
Created October 11, 2016 14:17
Show Gist options
  • Save truseed/edd6ca531ecc34dc6f7fe66d3fb4ac32 to your computer and use it in GitHub Desktop.
Save truseed/edd6ca531ecc34dc6f7fe66d3fb4ac32 to your computer and use it in GitHub Desktop.
//We will create a function to be extended to all String Objects
//This Injects the function into the String Object so any String Object will be able to call count
String.prototype.count = function countV() {
//store Object
var StringObj = this;
//Because countV is a function that will extend the String Object this will refer to the String itself if
//Our Json Object to Hold Data this is more efficient as you can return multiple results in one Object
var letter = { vowel: 0, consonant: 0 };
//Our loop
for (var i = 0; i < StringObj.length; i++) //Remember StringObj holds the String Object
{
//This will compare the characters and determine which is consonant and vowel by updating the Json Object
if (StringObj[i] == "a" || StringObj[i] == "e" || StringObj[i] == "i" || StringObj[i] == "o" || StringObj[i] == "u")
letter.vowel++; //increment the data by 1 if vowel found
else
letter.consonant++; //increment the data by 1 if consonant found
}
//do not use this.letter because this means String and letter is not an Object of String its an inner variable so we simple use letter
return letter;
};
//Testing Our function
var r = new String("Welcome");
console.log(r.count()) //returns the letter Json data
console.log(r.count().vowel) //returns vowel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment