0.1.0 • Published 7 years ago

@lato/from-function-prototype v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
7 years ago

@lato/from-function-prototype

A trick to make ordinary functions have its own prototype.

Example usage

import { fromFunctionPrototype } from '@lato/from-function-prototype';

const Maybe = fromFunctionPrototype(_ => "");

const nothing = new Maybe((n, j) => n(null));
const just = x => new Maybe((n, j) => j(x));

Now nothing and just(42) all share the same prototype which naturally can have new methods added:

Maybe.prototype.map = function(...) { ... };

but more importantly they behave as normal callable functions (in this example - to pattern match):

const perhapsANumber = just(42);

perhapsANumber(
  _ => console.log("nothing inside"),
  n => console.log(n, "inside")
);

Function passed to fromFunctionPrototype becomes .toString. For Maybe it could be:

const Maybe = fromFunctionPrototype(m => m(
  _ => "nothing",
  x => `just(${x.toString()})`
));

Use fromPrototype to extend other prototypes:

const Parent = function(){};
Parent.prototype = {
  foo: function() { console.log(this(18)); }
};

const Child = fromPrototype(Parent.prototype);

const v = new Child(x => x + 90);

v(4);                  // returns 94
v.foo();               // prints 108
v instanceof Parent;   // returns true
v instanceof Child;    // returns true
v instanceof Function; // returns false

Properties

If

const T = fromFunctionPrototype(...);
const f = ...;
const g = new T(f);

then

g instanceof Function;
g instanceof T;
typeof g === "function";
Object.getPrototypeOf(g) === T.prototype;
g.constructor === T;
f(...args) === g(...args); // for any args
0.1.0

7 years ago

0.0.2

7 years ago