Skip to content

matthewwithanm/wrapperator.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JavaScript decorators are cool and powerful, but usually you just want to replace the method with a wrapped version. wrapperator makes it easy to do that—and still use the same wrapper on normal functions.

Installation

npm install wrapperator

Usage

Create a function that wraps another, like normal:

function sayHi(fn) {
  return function wrapper(...args) {
    console.log('hi');
    return fn.apply(this, ...args);
  };
}

Then create a wrapperator from it:

import wrapperator from 'wrapperator';
sayHi = wrapperator(sayHi);

Now use it as a wrapper or a method decorator:

class K {
  @sayHi // Used as a method decorator.
  f() { console.log('f!'); }
}

new K().f(); // Logs "hi" and "f!"

const g = sayHi(() => console.log('g!')); // Used as a wrapper
g(); // Logs "hi" and "g!"

You can also use function expressions to create wrapperators in one step:

const sayHi = wrapperator(function(fn) {
  return function wrapper(...args) {
    console.log('hi');
    return fn.apply(this, ...args);
  };
});

Or you can just use wrapperator to use your normal wrapper functions as decorators at the decoration point:

import decorate from 'wrapperator';

function sayHi(fn) {
  return function wrapper(...args) {
    console.log('hi');
    return fn.apply(this, ...args);
  };
}

class K {
  @decorate(sayHi)
  f() { console.log('f!'); }
}

About

Create a function that can be used as a wrapper or method decorator

Resources

License

Stars

Watchers

Forks

Packages

No packages published