Object.prototype.pipe() - Universal Method Chaining in JavaScript

In case you (or future readers) are still interested, it sounds like what you want here is GitHub - tc39/proposal-call-this: A proposal for a simple call-this operator in JavaScript. with the .. syntax option. For example:

function pipe(callback) { return callback(this); }

anything..pipe(x => x)

// String processing
"hello world    "
  .trim()
  ..pipe(str => `*${str}*`)
  .toUpperCase()

// Array transformations
[1, 2, 3, 4, 5]
  .filter(n => n > 2)
  ..pipe(arr => ({ sum: arr.reduce((a, b) => a + b, 0) }))
  ..pipe(({ sum }) => sum.toString())
  .padStart(5, '0');

// Object manipulation
const user = { name: 'John', age: 30 }
  ..pipe(obj => ({ ...obj, role: 'admin' }))
  ..pipe(x => console.log(x) ?? x)
  ..pipe(({ role }) => role)
  .toUpperCase();

No issues with null prototypes and doesn’t affect property access as in if (foo.pipe) bar().

1 Like