simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

README.md (15014B)


      1 # typed-function
      2 
      3 [![Version](https://img.shields.io/npm/v/typed-function.svg)](https://www.npmjs.com/package/typed-function)
      4 [![Downloads](https://img.shields.io/npm/dm/typed-function.svg)](https://www.npmjs.com/package/typed-function)
      5 [![Build Status](https://github.com/josdejong/typed-function/workflows/Node.js%20CI/badge.svg)](https://github.com/josdejong/typed-function/actions)
      6 
      7 Move type checking logic and type conversions outside of your function in a
      8 flexible, organized way. Automatically throw informative errors in case of
      9 wrong input arguments.
     10 
     11 
     12 ## Features
     13 
     14 typed-function has the following features:
     15 
     16 - Runtime type-checking of input arguments.
     17 - Automatic type conversion of arguments.
     18 - Compose typed functions with multiple signatures.
     19 - Supports union types, any type, and variable arguments.
     20 - Detailed error messaging.
     21 
     22 Supported environments: node.js, Chrome, Firefox, Safari, Opera, IE11+.
     23 
     24 
     25 ## Why?
     26 
     27 In JavaScript, functions can be called with any number and any type of arguments.
     28 When writing a function, the easiest way is to just assume that the function
     29 will be called with the correct input. This leaves the function's behavior on
     30 invalid input undefined. The function may throw some error, or worse,
     31 it may silently fail or return wrong results. Typical errors are
     32 *TypeError: undefined is not a function* or *TypeError: Cannot call method
     33 'request' of undefined*. These error messages are not very helpful. It can be
     34 hard to debug them, as they can be the result of a series of nested function
     35 calls manipulating and propagating invalid or incomplete data.
     36 
     37 Often, JavaScript developers add some basic type checking where it is important,
     38 using checks like `typeof fn === 'function'`, `date instanceof Date`, and
     39 `Array.isArray(arr)`. For functions supporting multiple signatures,
     40 the type checking logic can grow quite a bit, and distract from the actual
     41 logic of the function.
     42 
     43 For functions dealing with a considerable amount of type checking and conversion
     44 logic, or functions facing a public API, it can be very useful to use the
     45 `typed-function` module to handle the type-checking logic. This way:
     46 
     47 -   Users of the function get useful and consistent error messages when using
     48     the function wrongly.
     49 -   The function cannot silently fail or silently give wrong results due to
     50     invalid input.
     51 -   Correct type of input is assured inside the function. The function's code
     52     becomes easier to understand as it only contains the actual function logic.
     53     Lower level utility functions called by the type-checked function can
     54     possibly be kept simpler as they don't need to do additional type checking.
     55 
     56 It's important however not to *overuse* type checking:
     57 
     58 -   Locking down the type of input that a function accepts can unnecessarily
     59     limit its flexibility. Keep functions as flexible and forgiving as possible,
     60     follow the
     61     [robustness principle](http://en.wikipedia.org/wiki/Robustness_principle)
     62     here: "be liberal in what you accept and conservative in what you send"
     63     (Postel's law).
     64 -   There is no need to apply type checking to *all* functions. It may be
     65     enough to apply type checking to one tier of public facing functions.
     66 -   There is a performance penalty involved for all type checking, so applying
     67     it everywhere can unnecessarily worsen the performance.
     68 
     69 
     70 ## Load
     71 
     72 Install via npm:
     73 
     74     npm install typed-function
     75 
     76 
     77 ## Usage
     78 
     79 Here are some usage examples. More examples are available in the
     80 [/examples](/examples) folder.
     81 
     82 ```js
     83 var typed = require('typed-function');
     84 
     85 // create a typed function
     86 var fn1 = typed({
     87   'number, string': function (a, b) {
     88     return 'a is a number, b is a string';
     89   }
     90 });
     91 
     92 // create a typed function with multiple types per argument (type union)
     93 var fn2 = typed({
     94   'string, number | boolean': function (a, b) {
     95     return 'a is a string, b is a number or a boolean';
     96   }
     97 });
     98 
     99 // create a typed function with any type argument
    100 var fn3 = typed({
    101   'string, any': function (a, b) {
    102     return 'a is a string, b can be anything';
    103   }
    104 });
    105 
    106 // create a typed function with multiple signatures
    107 var fn4 = typed({
    108   'number': function (a) {
    109     return 'a is a number';
    110   },
    111   'number, boolean': function (a, b) {
    112     return 'a is a number, b is a boolean';
    113   },
    114   'number, number': function (a, b) {
    115     return 'a is a number, b is a number';
    116   }
    117 });
    118 
    119 // create a typed function from a plain function with signature
    120 function fnPlain(a, b) {
    121   return 'a is a number, b is a string';
    122 }
    123 fnPlain.signature = 'number, string';
    124 var fn5 = typed(fnPlain);
    125 
    126 // use the functions
    127 console.log(fn1(2, 'foo'));      // outputs 'a is a number, b is a string'
    128 console.log(fn4(2));             // outputs 'a is a number'
    129 
    130 // calling the function with a non-supported type signature will throw an error
    131 try {
    132   fn2('hello', 'world');
    133 }
    134 catch (err) {
    135   console.log(err.toString());
    136   // outputs:  TypeError: Unexpected type of argument.
    137   //           Expected: number or boolean, actual: string, index: 1.
    138 }
    139 ```
    140 
    141 
    142 ## Types
    143 
    144 typed-function has the following built-in types:
    145 
    146 - `null`
    147 - `boolean`
    148 - `number`
    149 - `string`
    150 - `Function`
    151 - `Array`
    152 - `Date`
    153 - `RegExp`
    154 - `Object`
    155 
    156 The following type expressions are supported:
    157 
    158 - Multiple arguments: `string, number, Function`
    159 - Union types: `number | string`
    160 - Variable arguments: `...number`
    161 - Any type: `any`
    162 
    163 
    164 ## API
    165 
    166 ### Construction
    167 
    168 A typed function can be constructed in two ways:
    169 
    170 -   Create from an object with one or multiple signatures:
    171 
    172     ```
    173     typed(signatures: Object.<string, function>) : function
    174     typed(name: string, signatures: Object.<string, function>) : function
    175     ```
    176 
    177 -   Merge multiple typed functions into a new typed function:
    178 
    179     ```
    180     typed(functions: ...function) : function
    181     typed(name: string, functions: ...function) : function
    182     ```
    183 
    184     Each function in `functions` can be either a typed function created before,
    185     or a plain function having a `signature` property.
    186 
    187 
    188 ### Methods
    189 
    190 -   `typed.convert(value: *, type: string) : *`
    191 
    192     Convert a value to another type. Only applicable when conversions have
    193     been defined in `typed.conversions` (see section [Properties](#properties)). 
    194     Example:
    195     
    196     ```js
    197     typed.conversions.push({
    198       from: 'number',
    199       to: 'string',
    200       convert: function (x) {
    201         return +x;
    202     });
    203     
    204     var str = typed.convert(2.3, 'string'); // '2.3' 
    205     ```
    206 
    207 -   `typed.create() : function`
    208 
    209     Create a new, isolated instance of typed-function. Example:
    210     
    211     ```js
    212     var typed = require('typed-function');  // default instance
    213     var typed2 = typed.create();            // a second instance
    214     ```
    215 
    216     This would allow you, for example, to have two different type hierarchies
    217     for different purposes.
    218 
    219 -   `typed.find(fn: typed-function, signature: string | Array) : function | null`
    220 
    221     Find a specific signature from a typed function. The function currently
    222     only finds exact matching signatures.
    223     
    224     For example:
    225     
    226     ```js
    227     var fn = typed(...);
    228     var f = typed.find(fn, ['number', 'string']);
    229     var f = typed.find(fn, 'number, string');
    230     ```
    231 
    232 -   `typed.addType(type: {name: string, test: function} [, beforeObjectTest=true]): void`
    233 
    234     Add a new type. A type object contains a name and a test function.
    235     The order of the types determines in which order function arguments are 
    236     type-checked, so for performance it's important to put the most used types 
    237     first. All types are added to the Array `typed.types`. 
    238     
    239     Example:
    240     
    241     ```js
    242     function Person(...) {
    243       ...
    244     }
    245     
    246     Person.prototype.isPerson = true;
    247 
    248     typed.addType({
    249       name: 'Person',
    250       test: function (x) {
    251         return x && x.isPerson === true;
    252       }
    253     });
    254     ```
    255 
    256     By default, the new type will be inserted before the `Object` test
    257     because the `Object` test also matches arrays and classes and hence
    258     `typed-function` would never reach the new type. When `beforeObjectTest`
    259     is `false`, the new type will be added at the end of all tests.
    260 
    261 -   `typed.addConversion(conversion: {from: string, to: string, convert: function}) : void`
    262 
    263     Add a new conversion. Conversions are added to the Array `typed.conversions`.
    264     
    265     ```js
    266     typed.addConversion({
    267       from: 'boolean',
    268       to: 'number',
    269       convert: function (x) {
    270         return +x;
    271     });
    272     ```
    273 
    274     Note that any typed functions created before this conversion is added will
    275     not have their arguments undergo this new conversion automatically, so it is
    276     best to add all of your desired automatic conversions before defining any
    277     typed functions.
    278 
    279 -   `typed.createError(name: string, args: Array.<any>, signatures: Array.<Signature>): TypeError`
    280 
    281     Generates a custom error object reporting the problem with calling
    282     the typed function of the given `name` with the given `signatures` on the
    283     actual arguments `args`. Note the error object has an extra property `data`
    284     giving the details of the problem. This method is primarily useful in
    285     writing your own handler for a type mismatch (see the `typed.onMismatch`
    286     property below), in case you have tried to recover but end up deciding
    287     you want to throw the error that the default handler would have.
    288 
    289 ### Properties
    290 
    291 -   `typed.types: Array.<{name: string, test: function}>`
    292 
    293     Array with types. Each object contains a type name and a test function.
    294     The order of the types determines in which order function arguments are 
    295     type-checked, so for performance it's important to put the most used types 
    296     first. Custom types can be added like:
    297 
    298     ```js
    299     function Person(...) {
    300       ...
    301     }
    302     
    303     Person.prototype.isPerson = true;
    304 
    305     typed.types.push({
    306       name: 'Person',
    307       test: function (x) {
    308         return x && x.isPerson === true;
    309       }
    310     });
    311     ```
    312 
    313 -   `typed.conversions: Array.<{from: string, to: string, convert: function}>`
    314 
    315     An Array with built-in conversions. Empty by default. Can be used to define
    316     conversions from `boolean` to `number`. For example:
    317 
    318     ```js
    319     typed.conversions.push({
    320       from: 'boolean',
    321       to: 'number',
    322       convert: function (x) {
    323         return +x;
    324     });
    325     ```
    326 
    327     Also note the `addConversion()` method above for simply adding a single
    328     conversion at a time.
    329     
    330 -   `typed.ignore: Array.<string>`
    331 
    332     An Array with names of types to be ignored when creating a typed function.
    333     This can be useful to filter signatures when creating a typed function.
    334     For example:
    335 
    336     ```js
    337     // a set with signatures maybe loaded from somewhere
    338     var signatures = {
    339       'number': function () {...},
    340       'string': function () {...}
    341     }
    342 
    343     // we want to ignore a specific type
    344     typed.ignore = ['string'];
    345 
    346     // the created function fn will only contain the 'number' signature 
    347     var fn = typed('fn', signatures);
    348     ```
    349 
    350 -   `typed.onMismatch: function`
    351 
    352     The handler called when a typed-function call fails to match with any
    353     of its signatures. The handler is called with three arguments: the name
    354     of the typed function being called, the actual argument list, and an array
    355     of the signatures for the typed function being called. (Each signature is
    356     an object with property 'signature' giving the actual signature and\
    357     property 'fn' giving the raw function for that signature.) The default
    358     value of `onMismatch` is `typed.throwMismatchError`.
    359 
    360     This can be useful if you have a collection of functions and have common
    361     behavior for any invalid call. For example, you might just want to log
    362     the problem and continue:
    363 
    364     ```
    365     const myErrorLog = [];
    366     typed.onMismatch = (name, args, signatures) => {
    367       myErrorLog.push(`Invalid call of ${name} with ${args.length} arguments.`);
    368       return null;
    369     };
    370     typed.sqrt(9); // assuming definition as above, will return 3
    371     typed.sqrt([]); // no error will be thrown; will return null.
    372     console.log(`There have been ${myErrorLog.length} invalid calls.`)
    373     ```
    374 
    375     Note that there is only one `onMismatch` handler at a time; assigning a
    376     new value discards the previous handler. To restore the default behavior,
    377     just assign `typed.onMismatch = typed.throwMismatchError`.
    378 
    379     Finally note that this handler fires whenever _any_ typed function call
    380     does not match any of its signatures. You can in effect define such a
    381     "handler" for a single typed function by simply specifying an implementation
    382     for the `...` signature:
    383 
    384     ```
    385     const lenOrNothing = typed({
    386       string: s => s.length,
    387       '...': () => 0
    388     });
    389     console.log(lenOrNothing('Hello, world!')) // Output: 13
    390     console.log(lenOrNothing(57, 'varieties')) // Output: 0
    391     ```
    392 
    393 ### Recursion
    394 
    395 The `this` keyword can be used to self-reference the typed-function:
    396 
    397 ```js
    398 var sqrt = typed({
    399   'number': function (value) {
    400     return Math.sqrt(value);
    401   },
    402   'string': function (value) {
    403     // on the following line we self reference the typed-function using "this"
    404     return this(parseInt(value, 10));
    405   }
    406 });
    407 
    408 // use the typed function
    409 console.log(sqrt('9')); // output: 3
    410 ```
    411 
    412 
    413 ### Output
    414 
    415 The functions generated with `typed({...})` have:
    416 
    417 - A function `toString`. Returns well readable code which can be used to see
    418   what the function exactly does. Mostly for debugging purposes.
    419 - A property `signatures`, which holds a map with the (normalized)
    420   signatures as key and the original sub-functions as value.
    421 - A property `name` containing the name of the typed function, if it was
    422   assigned one at creation, or an empty string.
    423 
    424 
    425 ## Roadmap
    426 
    427 ### Version 2
    428 
    429 - Be able to turn off exception throwing.
    430 - Extend function signatures:
    431   - Optional arguments like `'[number], array'` or like `number=, array`
    432   - Nullable arguments like `'?Object'`
    433 - Create a good benchmark, to get insight in the overhead.
    434 - Allow conversions to fail (for example string to number is not always
    435   possible). Call this `fallible` or `optional`?
    436 
    437 ### Version 3
    438 
    439 - Extend function signatures:
    440   - Constants like `'"linear" | "cubic"'`, `'0..10'`, etc.
    441   - Object definitions like `'{name: string, age: number}'`
    442   - Object definitions like `'Object.<string, Person>'`
    443   - Array definitions like `'Array.<Person>'`
    444 - Improve performance of both generating a typed function as well as
    445   the performance and memory footprint of a typed function.
    446 
    447 
    448 ## Test
    449 
    450 To test the library, run:
    451 
    452     npm test
    453 
    454 
    455 ## Minify
    456 
    457 To generate the minified version of the library, run:
    458 
    459     npm run minify
    460 
    461 
    462 ## Publish
    463 
    464 1. Describe the changes in `HISTORY.md`
    465 2. Increase the version number in `package.json`
    466 3. Test and build:
    467     ```
    468     npm install
    469     npm run build
    470     npm test
    471     ```
    472 4. Verify whether the bundle and minified bundle works correctly by opening
    473    `./test/browser.html`  and `./test/browser.min.html` in your browser. 
    474 5. Commit the changes
    475 6. Merge `develop` into `master`, and push `master`
    476 7. Create a git tag, and pus this
    477 8. publish the library:
    478     ```
    479     npm publish
    480     ```