All examples By author By category About

aendra-rininsland

one-line arrow function syntax for getter/setter methods

Terse Configurable Functions

Originally forked from vijithassar/f6e3601eeb0ecf6c91e9b8c45eea7435

The function configuration methods from the reusable charts design pattern are both powerful and verbose, but their syntax can be condensed down to a one-liner by combining ES6 arrow functions, ternary operators, expression grouping, and the underscore variable convention for variadic functions. Note that this example will not work in Internet Explorer 11 or below.

Original syntax:

some_function.x = function(value) {
  if (!arguments.length) {
    return x;
  } else {
    x = value;
    return some_function;
  }
};

Condensed:

Object.defineProperty(some_function, 'x', {
    get: () => x,
    set: _ => (x = _, some_function),
});

This is a dense line of code, but brevity is beneficial here since this is an attempt to replace traditional function arguments with a more powerful semantic alternative.