1

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.

Roundearth
  • 11
  • 1
  • 2
    Could you post some of the code you've written? – gnerkus Jan 19 '16 at 05:26
  • This is not possible. How could it know that `multDiv(4)(3)(2)` should be a number, and `multDiv(2)(1)(1)` a function that can accept `(6)(3)(2)` before returning a number? You should be able to do it with something like `result(multDiv(4)(3)(2)) == 6` and `result(multDiv(2)(1)(1)(6)(3)(2)) == 8`. – Amadan Jan 19 '16 at 05:28

2 Answers2

3

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.

Antiokus
  • 534
  • 3
  • 8
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>
guest271314
  • 1
  • 15
  • 104
  • 177
  • See also http://stackoverflow.com/questions/27996544/how-to-correctly-curry-a-function-in-javascript/ , http://stackoverflow.com/questions/30198102/to-combine-functions-in-javascript-in-a-functional-way/ , http://stackoverflow.com/questions/33901793/writing-a-curried-javascript-function-that-can-be-called-an-arbitrary-number-of – guest271314 Jan 19 '16 at 07:13