Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
how to concatenate function with javascript closure and object

i'm trying to find a solution to this exercise:

Implement the calculate function that adds an object that gives the ability to do the four mathematical operations (addition, subtraction, multiplication and division) on the same number and finally print out the result.

function calculate() {

}

const calculator = calculate();
calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(calculator)

so, what is the right way to solve this (and if you can add comment will be appreciated

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

no need to put so many this and function...

in this way you have a closure value.
=> calc_00.val = 20;
will not change the result (it just add a new property if jso is not freeze ) or throw an error in strict mode

"use strict";

function calculate( initVal = 0 )  // default value is zero
  {
  let
    val = initVal    // closure value
  , jso =
    { add(v)         { val += v; return this }
    , sub(v)         { val -= v; return this }
    , multiply(v)    { val *= v; return this }
    , divide(v)      { val /= v; return this }
    , printResult()  { return val }
    }
  Object.freeze(jso)
 
  return jso
  }

const
  calc_00 = calculate()
, calc_10 = calculate(10)
  ;

// calc_00.yop = ()=>null; // Uncaught TypeError: can't define property "yop": Object is not extensible
// calc_00.sub = ()=>null; // Uncaught TypeError: "sub" is read-only
// calc_00.val = 20;       // Uncaught TypeError: can't define property "val": Object is not extensible

calc_00.add(2).add(4).multiply(3).sub(1).sub(3).divide(2);
calc_10.add(10).multiply(3);

console.log( calc_00.printResult(), calc_10.printResult() ) // 7 , 60

about 4 years ago · Juan Pablo Isaza Relatório

0

You can return the object itselft.

function calculate() {
  return {
    result: 0,
    add: function(num) {
      this.result += num;
      return this;
    },
    sub: function(num) {
      this.result -= num;
      return this;
    },
    multiply: function (num) {
      this.result *= num;
      return this;
    },
    divide: function (num) {
      this.result /= num;
      return this;
    },
    printResult: function () {
      return this.result;
    }
 }
};

const calculator = calculate();
const result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(result);

Make sure to understand how this works in JavaScript. For instance, using functions is different than using arrow functions.

Reference: JavaScript this

Alternative solution using closure

function calculate() {
  let result = 0;
  return {
    add: function(num) {
      result += num;
      return this;
    },
    sub: function(num) {
      result -= num;
      return this;
    },
    multiply: function (num) {
      result *= num;
      return this;
    },
    divide: function (num) {
      result /= num;
      return this;
    },
    printResult: function () {
      return result;
    }
 }
};

const calculator = calculate();
const result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda