retour au cours
Ce contenu n'est disponible que dans les langues suivantes :عربي, English, Español, فارسی, Indonesia, Italiano, 日本語, 한국어, Русский, Türkçe, Українська, 简体中文. Merci de
  • Please note how methods are stored. They are simply added to this.methods property.
  • All tests and numeric conversions are done in the calculate method. In future it may be extended to support more complex expressions.
function Calculator() {

  this.methods = {
    "-": (a, b) => a - b,
    "+": (a, b) => a + b
  };

  this.calculate = function(str) {

    let split = str.split(' '),
      a = +split[0],
      op = split[1],
      b = +split[2];

    if (!this.methods[op] || isNaN(a) || isNaN(b)) {
      return NaN;
    }

    return this.methods[op](a, b);
  };

  this.addMethod = function(name, func) {
    this.methods[name] = func;
  };
}

Ouvrez la solution avec des tests dans une sandbox.