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.

2
  • 2
    Could you post some of the code you've written? Commented Jan 19, 2016 at 5: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. Commented Jan 19, 2016 at 5:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.