Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created February 25, 2022 23:36
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 DavidWells/70b156702ed281a85abffa355d5c0817 to your computer and use it in GitHub Desktop.
Save DavidWells/70b156702ed281a85abffa355d5c0817 to your computer and use it in GitHub Desktop.
JS factory functions via a proxy
// https://github.com/Schniz/factoree
/**
* Creates a strict factory
*
* @param defaults the default values that would appear on all instances
*/
function factory(defaults) {
return attributes => {
const data = Object.assign(Object.assign({}, defaults), attributes);
const proxy = new Proxy(data, {
has(target, p) {
return target.hasOwnProperty(p);
},
ownKeys(target) {
return Reflect.ownKeys(target);
},
get(target, p) {
var _a;
if (((_a = target === null || target === void 0 ? void 0 : target.hasOwnProperty) === null || _a === void 0 ? void 0 : _a.call(target, p)) || target[p]) {
return target[p];
}
else if (isExceptionKey(p)) {
return undefined;
}
else {
throw new Error(`Can't access undefined key '${inspect(p)}' for object ${inspect(target)}`);
}
},
});
return proxy;
};
}
const JEST_INTERNAL_KEYS = [
Symbol.iterator,
Symbol.toStringTag,
'asymmetricMatch',
'nodeType',
'$$typeof',
'@@__IMMUTABLE_ITERABLE__@@',
'@@__IMMUTABLE_RECORD__@@',
];
const PROMISE_REQUIRED_KEYS = [
// See https://github.com/Schniz/factoree/issues/2
'then',
];
const EXCEPTION_KEYS_THAT_MUST_EXIST = [
...JEST_INTERNAL_KEYS,
...PROMISE_REQUIRED_KEYS,
];
function isExceptionKey(p) {
return EXCEPTION_KEYS_THAT_MUST_EXIST.indexOf(p) > -1;
}
const createUser = factory({ twitterHandle: undefined, tester: () => 'xyz' });
const gal = createUser({ name: 'Gal', twitterHandle: 'galstar' }); // => User
const joe = createUser({}); // => User
console.log(gal.tester())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment