Simulating Dart cascade notation

by Arnaud Buchholz

JavaScript

function cascade (obj) {
  const proxified = new Proxy(obj, {
    get(_, name) {
      const method = obj[name]
      if (typeof method === 'function') {
        return function () {
          obj[name].apply(this, arguments)
          return proxified
        }
      }
    }
  })
  return proxified
}

class Lars {
  deposit (amount) { console.log('+', amount)}
  withdraw (amount) { console.log('-', amount)}
  printAccount () { console.log('account')}
}

const lars = new Lars()

lars.deposit(1000)
lars.withdraw(1500)
lars.deposit(2000)
lars.printAccount()

cascade(lars)
  .deposit(1000)
  .withdraw(1500)
  .deposit(2000)
  .printAccount()