JS Coding Questions

Subscribe to my newsletter and never miss my upcoming articles

Q. Write a program to check for duplicates in an array, it the distance between two duplicate items it less than a specified amount.

const arr1 = [3, 1, 5, 7, 9, 5]; 

function checkDuplicates(arr, dis) {
    const map = {};

    for(let i = 0; i < arr.length; i++) {
        if(map[arr[i]]) {
            if(Math.abs(map[arr[i]] - (i + 1)) <= dis) {
                return true;
            }
        }

        map[arr[i]] = i + 1;
    }

    return false;
}

console.log('Result: ', checkDuplicates(arr1, 3));

Q. Write a curried version of a sum function which gives results like the 4 use cases mentioned below:

sum(1, 2, 3).sumOf(); // 6
sum(2, 3)(2).sumOf(); // 7
sum(1)(2)(3)(4).sumOf(); // 10
sum(2)(4, 1)(2).sumOf(); // 9

Explanation: This is a curried sum function, which returns a new sum function. This new function must have a property called sumOf which is a function that returns the sum of all elements passed as arguments to the function till the point is is called.

To achieve this, you need to store all the passed argument continuously in an array and return a sumOf function that can reduce the array to its sum.

function sum(...args) {
    let elements = [];

    if(args && args.length) {
        elements = [...elements, ...args];
    }

    const newFn = function(...args) {
         if(args && args.length) {
            elements = [...elements, ...args];
        }
        return newFn;
    }

    newFn.sumOf = () => {
        return elements.reduce((acc, obj) => acc + obj, 0);   
    }

    return newFn;
}

No Comments Yet