diff --git a/ex7/ex7.js b/ex7/ex7.js index 3a115e1..5b37eac 100644 --- a/ex7/ex7.js +++ b/ex7/ex7.js @@ -1,6 +1,6 @@ /** - * Write a function that returns the character that repeats itself the most in - * a given string. If there isn't one, returns null. + * mostFrequentChar returns the character that repeats itself the most in str. + * If there isn't one, returns null. * * For example: * mostFrequentChar("zuriel yahav") === "a" @@ -9,3 +9,70 @@ * mostFrequentChar("a b c d e f") === " " * mostFrequentChar("") === null */ + +function mostFrequentChar(str) { + + objCharCount = {}; + + if (str === '') { + return null; + } + + objCharCount = countChar(str); + + return getFrequentChar(objCharCount); +} + +function getFrequentChar(objCharCount) { + + var maxCount = 0, + frequentChar = null, + frequentCount = 0, + arrayChar = [], + currentCount = 0, + currentChar = ''; + + arrayChar = Object.keys(objCharCount); + + for (var i = 0; i < arrayChar.length; i++) { + + currentChar = arrayChar[i]; + currentCount = objCharCount[currentChar]; + + if (maxCount < currentCount) { + + maxCount = currentCount; + frequentChar = currentChar; + + } else if (maxCount === currentCount) { + + frequentChar = null; + + } + } + return frequentChar; +} + +function countChar(str) { + + var objCharCount = {}; + + for (var i = 0; i < str.length; i++) { + + // The char we are now working on + currentChar = str.charAt(i); + + if (objCharCount[currentChar] === undefined) { + + objCharCount[currentChar] = 1; + + } else { + + objCharCount[currentChar] = objCharCount[currentChar] += 1; + + } + } + return objCharCount; +} + +module.exports = mostFrequentChar; diff --git a/ex7/ex7Spec.js b/ex7/ex7Spec.js new file mode 100644 index 0000000..fbad527 --- /dev/null +++ b/ex7/ex7Spec.js @@ -0,0 +1,24 @@ +var mostFrequentChar= require('./ex7.js'); + +describe("mostFrequentChar", function() { + + it("finds one char that repeats the most", function(){ + expect(mostFrequentChar('zuriel yahav')).toBe('a'); + }); + + it("returns null because more than one char repeats twice", function(){ + expect(mostFrequentChar('ohad kravchick')).toBeNull(); + }); + + it("finds one char that repeats the most (3)", function(){ + expect(mostFrequentChar('dana kravchick')).toBe('a'); + }); + + it("finds a whitespace as the most frequent char", function(){ + expect(mostFrequentChar('a b c d e f')).toBe(' '); + }); + + it("returns null because input is empty", function(){ + expect(mostFrequentChar('')).toBeNull(); + }); +});