Roundearth
Roundearth

Reputation: 11

How to curry while handling arbitrary number of arguments in JavaScript?

A function multDiv that will do the following:

multDiv(4)(3)(2) --> 4 x 3 / 2 = 6

multDiv(2)(1)(1)(6)(3)(2) --> 2 x 1 / 1 x 6 / 3 x 2 = 8

The arguments are evaluated left to right with alternating multiplication and division.

Upvotes: 1

Views: 328

Answers (2)

guest271314
guest271314

Reputation: 1

An approach without use of currying; should be able to return same results using currying methods

function multDiv(n) {
  var r = 0
  , n = Array.isArray(n) ? n : Array.prototype.slice.call(arguments);
  n.forEach(function(_, i, array) {
    // multiply
    if (i % 2 === 0) {
      if (array[i + 1]) {
        if (r === 0) {
          r = array[i] * array[i + 1];
        } else {
          r *= array[i + 1]
        }
      }
    } else {
      // divide
      if (array[i + 1]) {
        r /= array[i + 1]
      }
    }
  });
  return r
}

// pass array or parameters; e.g., `[4,3,2]` or `4,3,2`
multDiv(4, 3, 2); // 6
multDiv([2, 1, 1, 6, 3, 2]); // 8

var inputs = document.querySelectorAll("input"),
  outputs = document.querySelectorAll("output");

for (var index = 0; index < outputs.length; index++) {
  var args = JSON.parse(inputs[index].value);
  outputs[index].innerHTML = multDiv(args)
}

function multDiv(n) {
  var r = 0,
    n = Array.isArray(n) ? n : Array.prototype.slice.call(arguments);
  n.forEach(function(_, i, array) {
    if (i % 2 === 0) {
      if (array[i + 1]) {
        if (r === 0) {
          r = array[i] * array[i + 1];
        } else {
          r *= array[i + 1]
        }
      }
    } else {
      if (array[i + 1]) {
        r /= array[i + 1]
      }
    }
  });
  return r
}
<fieldset>
  <input value="[4, 3, 2]" id="a" />result:
  <output for="a"></output>
  <br />
  <input value="[2, 1, 1, 6, 3, 2]" id="b" />result:
  <output for="b"></output>
</fieldset>

Upvotes: 1

Antiokus
Antiokus

Reputation: 544

I won't give the code - it's definitely doable. The issue is that you must return a function at each function call. So there's no way of just returning a number and that number also being a function.

I'd say add a tap method onto the function itself that would return the current value after series of multDiv operations are executed.

Upvotes: 3

Related Questions