Skip to content

Instantly share code, notes, and snippets.

@burdiuz
Last active May 28, 2018 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burdiuz/edee70ebb305dc6d6bd80ae522a7b169 to your computer and use it in GitHub Desktop.
Save burdiuz/edee70ebb305dc6d6bd80ae522a7b169 to your computer and use it in GitHub Desktop.
Wrapper over new Proxy() that adds handlers for apply and construct traps for function targets.

withProxy

Factory generator for wrapping objects with Proxy. Applies construct and apply traps to function targets.

const myFactory = withProxy({
  get: myGetHandler,
  set: mySetHandler,
  apply: myApplyHandler,
  construct: myConstructHandler,
});

const myWrappedFunction = myFactory(() => null); // gets all traps
const myWrappedObject = myFactory({}); // does not get "apply" and "construct" traps
{
"name": "@actualwave/with-proxy",
"description": "Wrapper over new Proxy() that adds handlers for apply and construct traps for function targets.",
"version": "0.0.1",
"main": "with-proxy.js",
"keywords": [
"js",
"javascript",
"proxy",
"apply",
"construct",
"factory",
"traps"
],
"homepage": "https://gist.github.com/burdiuz/edee70ebb305dc6d6bd80ae522a7b169",
"bugs": {
"url": "https://gist.github.com/burdiuz/edee70ebb305dc6d6bd80ae522a7b169",
"email": "burdiuz@gmail.com"
},
"license": "MIT",
"author": "Oleg Galaburda <burdiuz@gmail.com> (http://actualwave.com/)",
"dependencies": {
"@actualwave/is-function": "^0.0.1"
}
}
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const { isFunction } = require('@actualwave/is-function');
const withProxy = (handlers) => {
/*
have problems with using rest operator here, when in node_modules without additional
configurations, so using old style code
*/
const { apply, construct } = handlers;
delete handlers.apply;
delete handlers.construct;
const functionHandlers = { ...handlers, construct, apply };
return (target) => new Proxy(target, isFunction(target) ? functionHandlers : handlers);
};
exports.withProxy = withProxy;
exports.default = withProxy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment