JavaScript coding question
Simple

1. implement curry()

Currying is a useful technique used in JavaScript applications.

Please implement a curry() function, which accepts a function and return a curried one.

Here is an example

const join = (a, b, c) => {
   return `${a}_${b}_${c}`
}
 
const curriedJoin = curry(join)
 
curriedJoin(1, 2, 3) // '1_2_3'
 
curriedJoin(1)(2, 3) // '1_2_3'
 
curriedJoin(1, 2)(3) // '1_2_3'

solutions:

  1. The curry function takes a function (fn) as its parameter.
  2. If the number of arguments passed (args.length) is greater than or equal to the original function's arity (fn.length), then invoke fn with the spread syntax (...args) to pass all the collected arguments.
  3. If the number of arguments passed is not sufficient, then return an anonymous function that also uses the rest parameter syntax (...args2).
  4. Once the necessary number of arguments is met, the original function (fn) is called with all the accumulated arguments.

You can see my github file js/simple/curry.js (opens in a new tab)

function curry(fn) {
  return function curryInner(...args) {
    if(args.length >= fn.length) return fn(...args);
    return (...args2) => curryInner(...args, ...args2);
  }
}

2. implement Array.prototype.flat()

There is already Array.prototype.flat() in JavaScript (ES2019), which reduces the nesting of Array.

Could you manage to implement your own one?

Here is an example to illustrate

const arr = [1, [2], [3, [4]]];
flat(arr)
// [1, 2, 3, [4]]
flat(arr, 1)
// [1, 2, 3, [4]]
flat(arr, 2)
// [1, 2, 3, 4]

solutions:

  1. Recursive solution
function flat(arr, depth = 1) {
  let res = [];
  arr.forEach(item => {
    if (Array.isArray(item) && depth > 0) {
      // you can use concat
      // res = res.concat(flat(item, depth - 1));
      res = [...res, ...flat(item, depth - 1)];
    } else {
      res.push(item)
    }
  })
  return res;
}
  1. Recursive solution by reduce
function flat(arr, depth = 1) {
  return depth ? arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? flat(cur, depth - 1) : cur), []) : arr;
}
  1. Iterative solution by storing depth to queue
function flat(arr, depth = 1) {
  let queue = arr.map(item => [item, depth]);
  let res = [];
  while (queue.length > 0) {
    const [item, itemDepth] = queue.shift();
    if (Array.isArray(item) && itemDepth > 0) {
      queue.push(...item.map(i => [i, itemDepth - 1]))
    } else {
      res.push(item);
    }
  }
  return res;
}