ut1l
A small utility library for JavaScript.
Usage
Browser
To use the library in the browser, you need to include this JavaScript file:
It exports the global ut1l
object.
You can create alias variables (used by the examples below):
var O = ut1lcreateobject T = ut1lcreatethrowable;
The following browsers are tested:
Node.js
Install this package with:
npm install ut1l
You can create alias variables (used by the examples below):
var O = T = ;
Examples
Object creation
If you are not a big fan of classical inheritance in JavaScript and want to create multiple similar objects you can do e.g. like this:
var person bill; { return firstName: firstName lastName: lastName }; bill = ; console; // Bill
But sometimes you want to know if an object is of some given “type”. This can be done with instanceof
which is supported by this lib:
person = ; bill = ; console; // Billconsole; // true
You can also specify an object which should be used as prototype:
person = ; bill = ; console; // Billconsole; // true console; // Bill Gates
An additional object can be passed as first parameter which fields will be available in the returned constructor:
person = ; bill = ; console; // Billconsole; // trueconsole; // Bill Gates console; // true
Throwables
You can create and use throwables like this:
var myThrowable = // top level throwable constructor mySubThrowable = ; // sub throwable constructor // ...if somethingBadHappened throw ;
It is easy to build a type tree of throwables if needed. They work with instanceof
and the thrown objects have a stack property if this is supported by the interpreter.
Additionally to try...catch
throwables can be caught like this:
actionProxy = T;
The action function is proxied and all given throwable types (and their sub types) are caught for this action. If no throwable type is given, all throwables are caught.
A combined example:
var notANumber divide; // create new throwable typenotANumber = ; // create division function which throws on division by zero { if b === 0 throw ; return a / b;}; // proxy division function which handles all NotANumber errorsdivide = T; console; // 0.5console; // 42