A safe .pipe() method using ES6 Symbols

David James Knight
12 Sep 2018

Use an ES6 Symbol to invoke a pipe function without the potential conflicts caused by monkeypatching a custom method onto the Object prototype.

Code

const pipeFunc = obj => fns => fns.reduce((x, f) => f(x), obj) 
const pipe = Symbol("pipe")
Object.prototype[pipe] = function(...fns) { return pipeFunc(this)(fns) }

Usage example

const computed_width = "426.5px"

const width = (el) => el[pipe]( 
  x => x.replace('px', ''),
  parseFloat,
  Math.ceil
)

console.log(width(computed_width))

// Returns 426

Compare to a nested function

const width = Math.ceil(parseFloat(window.getComputedStyle(document.querySelector('body')).width.replace('px', '')))

Compare to a step-by-step approach using intermediate variables

const body = document.querySelector('body')
const computed_width = window.getComputedStyle(body).width
const width_str = computed_width.replace('px', '')
const width_float = parseFloat(width_str)
const width = Math.ceil(width_float)

Performance

Piped: 0.004ms
Nested: 0.008ms
Step-by-step: 0.170ms