
Javascript Prototype Library
This collection of native-type prototype extensions in Javascript helps make expressions
more terse and improves legibility. The argument could be made that its use is unadvisable
within browsers as your mileage may vary due to the instability of these implementations,
but in NodeJs it works (and comes with a test suite)
Install / Import
The project is published on NPM so install is easy:
npm install js-prototype-lib
...and to use in your projects, simply import it:
const jsp = require('js-prototype-lib');
jsp.install();
jsp.install('object');
jsp.install('array', 'string');
console.log([1,2,3].last());
jsp.uninstall('object');
jsp.uninstall();
Extensions
The prototype extensions provided are documented separately by root object:
Errors
Errors are not easily examinable, thus attempting to create a Json string from one will fail.
By installing the error module it is possible to extract the object within an error:
const jsp = require('js-prototype-lib')
jsp.install('error')
try {
throw new Error('test')
}
catch(e) {
console.log(JSON.stringify(e))
console.log(JSON.stringify(e.obj()))
console.log(e.json())
}
Common
The objects Array, String Object and Number have also been marked up with properties
that facilitate determining their type. This short-circuits the need to do typeof x == '...'
comparisons, which is inconsistent with arrays where the result is 'object'. Additionally, the
.typeof
property is also defined for each object
Below are the properties available:
var x = '';
console.log(x.isStr);
console.log(x.isArr);
console.log(x.isObj);
console.log(x.isNbr);
console.log(x.typeof);
x = [];
console.log(x.isStr);
console.log(x.isArr);
console.log(x.isObj);
console.log(x.isNbr);
console.log(x.typeof);
x = {};
console.log(x.isStr);
console.log(x.isArr);
console.log(x.isObj);
console.log(x.isNbr);
console.log(x.typeof);
x = 0;
console.log(x.isStr);
console.log(x.isArr);
console.log(x.isObj);
console.log(x.isNbr);
console.log(x.typeof);
Notes
As this module may be included at multiple levels of a project (a project includes it but a dependency
of the project also includes it), and the versions at each level differ, the codebase makes sure that
only the latest version available is installed.
To accomplish this the Array, Object and String objects are marked up with the attributes library
and version
, thus to check what version is loaded you can:
const jsp = require('js-prototype-lib')
console.log(jsp.version().SemVer)
jsp.install('string')
console.log(String.version)
both of which could show:
1.0.11
Contribute
If you have an extension you're fond of, post an issue on Github. We're happy to add new
functionality. If you clone this repo and make changes, make sure to add tests for your changes
and generate a Pull Request only when they pass. You can run like this:
npm test
If you decide to publish on NPM this command should do it:
npm version <patch|minor|major>
Licence
MIT