Last active
June 28, 2022 14:38
-
-
Save vpellegrino/27f9a50ab635e48e0f07a4cf1c09c2cd to your computer and use it in GitHub Desktop.
Task: Write some code that, giving an array of strings, returns the number of occurrences where at least a char is repeated.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* production code | |
*/ | |
const _countOccurrences = charMap => { | |
let occ = 0; | |
for (let char in charMap) { | |
if (charMap[char] >= 2) { | |
occ++; | |
} | |
} | |
return occ; | |
} | |
const _occurrencesInAString = str => { | |
const charMap = {}; | |
for (let char of str){ | |
if (!charMap[char]) { | |
charMap[char] = 1; | |
} else { | |
charMap[char]++; | |
} | |
} | |
return _countOccurrences(charMap); | |
}; | |
const occurrences = words => { | |
if (!words || !words.length) { | |
return 0; | |
} | |
return Math.max(...words.map(word => _occurrencesInAString(word))); | |
} | |
/** | |
* unit tests | |
*/ | |
mocha.setup('bdd'); | |
const assert = chai.assert; | |
describe('given an array, counting its occurrences', () => { | |
describe('when no character is repeated', () => { | |
it('should return 0', function () { | |
assert.equal(occurrences(["a","b","c"]), 0); | |
}); | |
}); | |
describe('when just 1 character is repeated in just one string', () => { | |
it('should return 1', function () { | |
assert.equal(occurrences(["a","b","cc"]), 1); | |
}); | |
}); | |
describe('when just 1 character is repeated in different strings', () => { | |
it('should return 1', function () { | |
assert.equal(occurrences(["a","bb","cc"]), 1); | |
}); | |
}); | |
describe('when 2 characters are repeated in just one string', () => { | |
it('should return 2', function () { | |
assert.equal(occurrences(["ABC","deef","hi", "mnmn"]), 2); | |
}); | |
}); | |
describe('when 2 characters are repeated in different strings', () => { | |
it('should return 2', function () { | |
assert.equal(occurrences(["ABC","ddeef","hii", "mnmn"]), 2); | |
}); | |
}); | |
describe('when it is empty', () => { | |
it('should return 0', function () { | |
assert.equal(occurrences([]), 0); | |
}); | |
}); | |
describe('when it is null or undefined', () => { | |
it('should return 0', function () { | |
assert.equal(occurrences(null), 0); | |
assert.equal(occurrences(undefined), 0); | |
}); | |
}); | |
}); | |
mocha.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment