[SOLVED] In native Javascript (or NodeJS) is it possible to chain object or function properties for a function call?

Issue

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...
}

Solution

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.

Answered By – jabaa

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *