简体   繁体   中英

Is there a javascript universal chaining method

WARNING: Axios is broken if you use this, but fetch is not.

For short I'm asking if there is a standard way to chain functions independently of type, with a similar implementation which doesn't polute Native Prototypes:

 Object.prototype.pipe = function (func) { return func(this) }

Edit: Use the following if you want to avoid enumerable bugs where the method would appear when enumerating keys of any object, also it's a loose defined method.

Object.defineProperty(Object.prototype, 'pipe', {
    value(func) {
        return func(this)
    }
})

This would permit to do thing like :

const preloadContext = require.context('@/', true, /\.preload\.vue$/)
const preloadComponents = preloadContext
   .keys()
   .map(fileName => {
      const name = fileName
         .split('/')
         .pop()
         .replace(/\.\w+.\w+$/, '')
         .pipe(camelCase)
         .pipe(upperFirst)
      const component = filename
         .pipe(preloadContext)
         .pipe(config => config.default || config)
      Vue.component(name, component)
      return [name, component]
   })
   .pipe(Object.fromEntries)

instead of

const preloadContext = require.context('@/', true, /\.preload\.vue$/)
const preloadComponents = Object.fromEntries(preloadContext
   .keys()
   .map(fileName => {
      const name = upperFirst(camelCase(fileName
         .split('/')
         .pop()
         .replace(/\.\w+.\w+$/, '')
      ))
      const config = preloadContext(fileName)
      const component = config.default || config
      Vue.component(name, component)
      return [name, component]
   })
)

No, there's no real standard way. There's a stage 1 proposal for an operator that would do it , though:

const name = fileName
   .split('/')
   .pop()
   .replace(/\.\w+.\w+$/, '')
   |> camelCase
   |> upperFirst

which you can use today with rewriting tools like Babel .

If you don't want to use a rewriting tool, though, I definitely wouldn't create Object.prototype.pipe . There are still cleaner non-ideal options:

const pipe = (value, fns) =>
    fns.reduce((acc, fn) => fn(acc), value);

 const pipe = (value, fns) => fns.reduce((acc, fn) => fn(acc), value); const foo = pipe('Mzg0MA==', [ atob, Number, x => x.toString(16), ]); console.log(foo);

(Lots of helpful function collections and individual packages implement this.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM