Most of these questions are taken from bigfrontend.dev. A great website for practicing JavaScript and preparing for frontend interviews.
- Implement curry()
function curry(fn) {
return function curryInner(...args) {
if (args.length >= fn.length) return fn(...args);
return (...args2) => curryInner(...args, ...args2);
};
}
// USAGE ↓
// Utility function that will be curried
const log = (date, importance, message) => {
return `${date}:${importance}:${message}`
}
const curryLog = curry(log)
console.log(curryLog(new Date(), "INFO", "hello world")) // date:INFO:hello world
console.log(curryLog(new Date())("INFO")("hello world")) // date:INFO:hello world
const logNow = curryLog(new Date())
console.log(logNow("INFO", "hello world")) // date:INFO:hello world
- create a sum
const sum = (num) => {
const func = (num2) => {
return num2 ? sum(num+num2) : num
}
func.valueOf = () => num
return func;
}
// USAGE ↓
const sum1 = sum(1)
console.log(sum1(3).valueOf()) // 4
console.log(sum1(1) == 2) // true
console.log(sum(1)(2)(3) == 6) // true
- remove characters
const removeChars = (input) => {
const regExp = /b|ac/g
while (regExp.test(input)) {
input = input.replace(regExp, "")
}
return input
}
// USAGE ↓
removeChars("ab") // "a"
removeChars("abc") // ""
removeChars("cabbaabcca") // "caa"