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

153
Visualizações
In native Javascript (or NodeJS) is it possible to chain object or function properties for a function call?

More of an exercise in 'what-if', I was wondering if the following was possible:

output = convert(1200).from('mm').to('inches')

where 'from' and 'to' are functions (or properties) of 'convert' as opposed to the more standard:

    output = convert(1200, 'mm', 'inches')

or:

    output = convert(value = 1200, from = 'mm', to = 'inches')

addendum: I'm guessing the closest would be:

output = convert({ value: 1200, from: 'mm', to: 'inches' });
 
function convert({ value, from, to } = {}){
  // ...do stuff here...
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Yes, it's possible. Example:

function convert(val) {
  const units = {
    mm: 1,
    cm: 10,
    dm: 100,
    m: 1000,
    in: 25.4,
    inches: 25.4,
    inch: 25.4,
    ft: 304.8,
    feet: 304.8,
    foot: 304.8,
    yd: 914.4,
    yard: 914.4,
    yards: 914.4
  }
  return {
    from(unit1) {
      return {
        to(unit2) {
          return val * units[unit1] / units[unit2];
        }
      };
    }
  };
}

const output = convert(1200).from('mm').to('inches');

console.log(output);

console.log(convert(47.24409448818898).from('inches').to('mm'));
console.log(convert(123).from('m').to('yards'));

convert returns an object with a from method. from returns an object with a to method. to returns a number. The temporary values are stored in a closure.

about 4 years ago · Juan Pablo Isaza Relatório

0

Create an object constructor with the convert, from and to functions, and properties to store the values passed to each corresponding function when called. In both convert and from functions, return the instance via 'return this' and return the answer in the to function.

https://www.w3schools.com/JS/js_object_constructors.asp

function Converter() {
  this.value = 0;
  this.fromUnit = '';
  this.toUnit = '';
  this.convert = function(value) {
   ... 
   return this
  } 
 this.from = function(unit) {... return this} 
 this.to = function(unit) {... return answer} 
}

const converter = new Converter()
converter.convert(...).from(...).to(...)

You can also follow the Class syntax on ES6 JavaScript. https://www.w3schools.com/Js/js_classes.asp

about 4 years ago · Juan Pablo Isaza Relatório

0

Treating this as a syntax rather than a design question, here is an ugly but working solution.

However, I would like to encourage you to refactor it or reconsider whether this functional API is necessary.

const convert = (num) => ({
  from: (inputUnit) => {
    switch (inputUnit) {
      case "mm":
        return {
          to: (outputUnit) => {
            switch (outputUnit) {
              case "inches":
                return num / 25.4;
            }
          },
        };
    }
  },
});

console.log(
  convert(1200).from("mm").to("inches")
)

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