Skip to content

Commit

Permalink
Add ExtensibleFunction class (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
kristw authored and zhaoyongjie committed Nov 24, 2021
1 parent b250633 commit c8e3256
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { default as ExtensibleFunction } from './models/ExtensibleFunction';
export { default as Plugin } from './models/Plugin';
export { default as Preset } from './models/Preset';
export { default as Registry } from './models/Registry';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* From https://stackoverflow.com/questions/36871299/how-to-extend-function-with-es6-classes
*/

export default class ExtensibleFunction extends Function {
constructor(fn) {
return Object.setPrototypeOf(fn, new.target.prototype);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
ExtensibleFunction,
Plugin,
Preset,
Registry,
Expand All @@ -12,6 +13,7 @@ import {
describe('index', () => {
it('exports modules', () => {
[
ExtensibleFunction,
Plugin,
Preset,
Registry,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import ExtensibleFunction from '../../src/models/ExtensibleFunction';

describe('ExtensibleFunction', () => {
class Func1 extends ExtensibleFunction {
constructor(x) {
super(() => x); // closure
}
}
class Func2 extends ExtensibleFunction {
constructor(x) {
super(() => this.x); // arrow function, refer to its own field
this.x = x;
}

hi() {
return 'hi';
}
}
class Func3 extends ExtensibleFunction {
constructor(x) {
super(function customName() {
return customName.x;
}); // named function
this.x = x;
}
}

it('its subclass is an instance of Function', () => {
expect(Func1).toBeInstanceOf(Function);
expect(Func2).toBeInstanceOf(Function);
expect(Func3).toBeInstanceOf(Function);
});

const func1 = new Func1(100);
const func2 = new Func2(100);
const func3 = new Func3(100);

it('an instance of its subclass is executable like regular function', () => {
expect(func1()).toEqual(100);
expect(func2()).toEqual(100);
expect(func3()).toEqual(100);
});

it('its subclass behaves like regular class with its own fields and functions', () => {
expect(func2.x).toEqual(100);
expect(func2.hi()).toEqual('hi');
});

it('its subclass can set name by passing named function to its constructor', () => {
expect(func3.name).toEqual('customName');
});
});

0 comments on commit c8e3256

Please sign in to comment.