Question 1
Javascript function indexOf
returns -1 if there is no match in the string, not a falsy value. The following code can resolve the issue.
function validateString(str) {
if (str.toLowerCase().indexOf('superman') === -1) {
throw new Error('String does not contain superman');
}
}
Question 2
function isInArray(arr, val) {
return arr.findIndex((item) => item === val) !== -1
}
Question 3
function formatPhoneNumber(str, delimiter = '-') {
const cleaned = ('' + str).replace(/\D/g, '');
const match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
if (match) {
const intlCode = (match[1] ? '+1 ' : '');
return [match[2], match[3], match[4]].join(delimiter);
}
return null;
}
Question 4
describe('fizzBuzz function test cases', () => {
test("stop is smaller than start, should throw an invalid arguments error", () => {
expect(() => fizzBuzz(50, 2)).toThrow("Invalid arguments");
});
test("start is smaller than 0, should throw an invalid arguments error", () => {
expect(() => fizzBuzz(-10, 2)).toThrow("Invalid arguments");
});
test("stop is smaller than 0, should throw an invalid arguments error", () => {
expect(() => fizzBuzz(50, -10)).toThrow(new Error('Invalid arguments'));
});
test("In case there is no multiplier of 3 or 5 - 1, 2", () => {
expect(fizzBuzz(1, 2)).toBe("12");
});
test("In case there is multiplier of 3 should append Fizz", () => {
expect(fizzBuzz(8, 9)).toBe("8Fizz");
});
test("In case there is multiplier of 5 should append Buzz", () => {
expect(fizzBuzz(10, 11)).toBe("Buzz11");
});
test("In case there are multipliers of 3 and 5 should include Buzz and Fizz", () => {
expect(fizzBuzz(3, 5)).toBe("Fizz4Buzz");
});
});
Question 5
First of all, I used hash function to get the unique integer value from string as defined in hashCode
. It returns the same value for the same string.
Function intToRGB
is now to convert the integer into hexadecimal less than 0xFFFFFF
with 0
s padded to make it 6 length string.
function hashCode(str) {
let hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function intToRGB(i) {
const c = (i & 0x00FFFFFF).toString(16).toUpperCase();
return "#00000".substring(0, 7 - c.length) + c;
}
function stringToHexColor(str) {
return intToRGB(hashCode(str))
}
Question 6
When we click button, i
is already 10. To resolve the issue, we need to bind scope to each iteration
(function() {
for (var i = 0, l = 10; i < l; i++) {
(function(j) {
document.getElementById('button-' + j).onclick = function () {
console.log('Line %s', j);
};
})(i)
}
})();
Question 7
function isIterable(obj) {
return obj != null && typeof obj[Symbol.iterator] === 'function';
}