function singleDifferentChar(str1, str2) {
if (typeof str1 !== 'string' || typeof str2 !== 'string') {
throw new Error(`One or both of your inputs is not a string. Please use two strings - str1: ${str1} str2: ${str2} `);
}
const str1CharCount = getCharCountMap(str1);
const str2CharCount = getCharCountMap(str2);
return findDifference(str1CharCount, str2CharCount)
}
function getCharCountMap(string) {
return string.split('').reduce((map, char) => {
map[char] = map[char] + 1 || 1;
return map;
}, {})
}
function findDifference(map1, map2) {
const largestMap = Object.keys(map1).length >= Object.keys(map2).length ? map1 : map2;
for (let key in largestMap) {
const isDifferent = map1[key] !== map2[key];
if (isDifferent) return key;
}
}
function findDiff(str1, str2) {
if (str1 === null || str2 === null) {
throw new Error('str1 or str2 cannot be null');
}
let result = 0;
for (let i = 0; i < str1.length; i++) {
result ^= str1.charCodeAt(i)
}
for (let i = 0; i < str2.length; i++) {
result ^= str2.charCodeAt(i)
}
return String.fromCharCode(result);
}
function runTests(func) {
const inputOutput = [['abcd', 'abcde', 'e'], ['aaabbcdd', 'abdbacade', 'e']];
for (let i = 0; i < inputOutput.length; i++) {
const input = inputOutput[i].slice(0, inputOutput[i].length-1);
const expected = inputOutput[i][inputOutput[i].length-1];
const result = func(...input);
if (result !== expected) {
return [false, result, expected];
}
}
return [true];
}
let throwsErrorCorrectly = false;
let runsTestSuccessfully = false;
let result, expected;
try {
singleDifferentChar(null, 'input');
} catch (e) {
[runsTestSuccessfully, result, expected] = runTests(singleDifferentChar);
throwsErrorCorrectly = true;
} finally {
const message = runsTestSuccessfully && throwsErrorCorrectly ? 'All tests passed' : `Expected: ${expected}. Got ${result}`;
console.log(message);
}