Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
Writing a calculator function - in the most functional programming way(javascript)

I am trying out a task from codewars and wanted to write in a functional programming way in javascript. I have some questions regarding my functions and how the code can be written in a better way.

The task itself is to build a calculator function. It will accept an input in the format:

'..... + ...'

The calculator must split the string by the middle character signifying the operation and then the two string that are left will be the two values. In the example above first value will be 5 and the second 3. Once this is done, depending on the operator, do the action - either addition, multiplication etc.

Here is my code:

function dotCalculator(equation) {

    function returnSymbol(input) {

        if (input.includes(' + ')) {
            return ' + ';
        } else if (input.includes(' - ')) {
            return ' - ';
        } else if (input.includes(' * ')) {
            return ' * ';
        } else if (input.includes(' / ')) {
            return ' / ';
        }

    }

    let symbolOf = returnSymbol;

    let result = equation.split(symbolOf(equation)).map(x => x.length);
    
    // Array.prototype.add = function(){
    //     return this[0] + this[1];
    // }
}

I know my code is not done yet. I am trying to understand how to properly finish it having the functional programming way of thinking in mind. Maybe prototypal inheritance would a bit overkill. I am looking for some ideas from anyone who would lend a hand. I tried writing a more complex reduce after

let arrMine = equation.split(symbolOf(equation)).map((x) => x.length);

but it seemed way too messy. Any help would be greatly appreciated.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I'm very much a functional programming noob, the pipe function being here is probably kind of gratuitous and I might have taken the ..... + ... example overly literally, but here's an attempt:

const arith = {
  '+': (a, b) => a + b,
  '-': (a, b) => a - b,
  '*': (a, b) => a * b,
  '/': (a, b) => a / b,
};

const pipe = (...fns) => (arg) => fns.reduce((res, fn) => fn(res), arg);

const get_input_elements = (input) => input.split(' ');

const get_number = (dots) => dots.length;

const get_numbers = ([str_a, op, str_b]) =>
  [get_number(str_a), op, get_number(str_b)];

const apply_arith = ([a, op, b]) => arith[op](a, b);

const calc = pipe(
  get_input_elements,
  get_numbers,
  apply_arith
);

console.log(calc('..... + ...'));
console.log(calc('..... - ...'));
console.log(calc('...... / ..'));

about 4 years ago · Juan Pablo Isaza Report

0

In this example are functional programs that can evaluate simple arithmetic -- adding, subtracting, multiplying, or dividing two numbers.

Details are commented in example below
Note: prefix any negative number being passed into calc() with an underscore _ instead of a hyphen -

// Utility function
const log = data => console.log(JSON.stringify(data));

// Arithmetic functions
const sum = (a, b) => (+a) + (+b);
const dif = (a, b) => a - b;
const pro = (a, b) => a * b;
const quo = (a, b) => a / b;

/**
 * Calculate a simple formula a+b, a-b, a*b, or a/b.
 * @param {string} formula - Pattern:
 *  "numberOPERANDnumber" ex. "5+5"
 *  Use an underscore to prefix negative numbers.
 * @returns {number} Result of formula
 */
const calc = formula => {
  // Declare variables
  let result, f, a, b, op;

  /*
  Convert string into an array of strings.
  [number, operand, number]
  Replace any _ with - (see @param)
  */
  f = formula.split(/([+\-*/])/)
    .map(ab => ab.replace('_', '-'));

  /*
  Convert string of numbers into real numbers.
  */
  a = parseFloat(f[0]);
  b = parseFloat(f[2]);
  op = f[1];

  /*
  Check if >a< and >b< are real numbers and if the input string was split 
  into 3 strings.
  */
  if (Number.isNaN(a) || Number.isNaN(b) || f.length != 3) {
    return;
  }

  // >op< determines the method of resolving the formula
  switch (op) {
    case '+':
      result = sum(a, b);
      break;
    case '-':
      result = dif(a, b);
      break;
    case '*':
      result = pro(a, b);
      break;
    case '/':
      result = quo(a, b);
      break;
    default:
      return;
  }
  return result;
};

log(calc('5+5'));
log(calc('_10-7')); // That's a -10 (see @param)
log(calc('5*9'));
log(calc('51/3'));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!