Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active May 31, 2020 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/5d67b164d11da6f26a4f4ae6cba7aec8 to your computer and use it in GitHub Desktop.
Save rauschma/5d67b164d11da6f26a4f4ae6cba7aec8 to your computer and use it in GitHub Desktop.

Functional decorators

Disclaimer: random thoughts of mine; not sure if they are useful.

Motivating example

class StringBuilder {
  #data = '';
  proto add = logged @ function (str) {
    this.#data += str;
  };
  proto toString = logged @ function () {
    return this.#data;
  };
}

function logged(func) {
  return function (this, ...args) {
    console.log(args);
    return func.call(this, ...args);
  };
}

New constructs

  • Prototype fields: proto key = value;

  • Function application operator: f @ x === f(x)

    • Alternative: postfix use of decorators via pipeline operator:
      proto add = function (str) {
        this.#data += str;
      } |> logged;
  • Optional this as an explicit parameter of universal functions:

    • Makes the use of this explicit in non-method functions.

Optional: this parameters for arrow functions

Turns arrow functions into methods:

class StringBuilder {
  #data = '';
  proto add = logged @ (this, str) => {
    this.#data += str;
  };
  proto toString = logged @ (this) => {
    return this.#data;
  };
}
function logged(func) {
  return (this, ...args) => {
    console.log(args);
    return func.call(this, ...args);
  };
}

Open questions

  • Can logged() access the names of the methods? Would be useful for logging!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment