Ad
Mathematics
Algorithms
Logic
Numbers
Code
Diff
  • function getResult(array, operator) {
      // WARNING! topicstarter gave wrong testcases! switch substract and rest values
      // to topicstarter: subsract is minus (-), not plus (+)
      if (!Array.isArray(array) || !array.length) { return false; }
      var array = array.slice();
      var operators = [
        'Rest',
        'Substract',
        'Multiply',
        'Divide'
      ];
      if (operators.indexOf(operator) === -1) { return false; }
      var res = array.find(function(elem) { // find first number in array
        return +elem === elem;
      });
      if (res === undefined) { return 0; }
      var idx = array.indexOf(res);
      array.splice(0, idx+1);
      var totalRes = array.reduce(function(acc, elem) {
        if (+elem !== elem) {
          return acc;
        }
        switch (operator) {
            case operators[0]:
              return acc += elem;
              break;
            case operators[1]:
              return acc -= elem;
              break;
            case operators[2]:
              return acc *= elem;
              break;
            default:
              return elem === 0 ? Infinity : acc /= elem;
              break;
        }
      }, res);
      return totalRes;
    }
    • function getResult(array, operator) {
    • test :D
    • // WARNING! topicstarter gave wrong testcases! switch substract and rest values
    • // to topicstarter: subsract is minus (-), not plus (+)
    • if (!Array.isArray(array) || !array.length) { return false; }
    • var array = array.slice();
    • var operators = [
    • 'Rest',
    • 'Substract',
    • 'Multiply',
    • 'Divide'
    • ];
    • if (operators.indexOf(operator) === -1) { return false; }
    • var res = array.find(function(elem) { // find first number in array
    • return +elem === elem;
    • });
    • if (res === undefined) { return 0; }
    • var idx = array.indexOf(res);
    • array.splice(0, idx+1);
    • var totalRes = array.reduce(function(acc, elem) {
    • if (+elem !== elem) {
    • return acc;
    • }
    • switch (operator) {
    • case operators[0]:
    • return acc += elem;
    • break;
    • case operators[1]:
    • return acc -= elem;
    • break;
    • case operators[2]:
    • return acc *= elem;
    • break;
    • default:
    • return elem === 0 ? Infinity : acc /= elem;
    • break;
    • }
    • }, res);
    • return totalRes;
    • }