Security News
The Push to Ban Ransom Payments Is Gaining Momentum
Ransomware costs victims an estimated $30 billion per year and has gotten so out of control that global support for banning payments is gaining momentum.
prototypes
Advanced tools
Readme
Some common prototypes for node.js: string.startsWith()
,
object.countProperties()
and more.
Functions are added using Object.defineProperty()
to avoid polluting new objects.
Includes nice facilities for functional programming with objects:
object.forEach()
, object.filterIn()
and so on.
Simply install using npm:
npm install prototypes
Or add to the dependencies of your project in your package.json
.
This package adds some useful prototypes to String
, Object
and Array
.
To use in your package, you just have to require prototypes:
require('prototypes');
There is no need to assign the result to any variable, since the prototypes are added automatically. It may in fact result in a warning in JSHint or similar code checkers.
Special care has been taken to avoid nasty interactions with other libraries: the new function prototypes don't appear in enumerations and can be overwritten in your own code.
The following string prototypes are provided.
Check that the current string starts with the given substring. Example:
'pepitus'.startsWith('pep');
\=> true
Check that the current string ends with the given substring. Example:
'pepitus'.endsWith('tus');
\=> true
Return the piece of string until the argument is found; return the whole string if not found. Example:
'hi.there'.substringUpTo('.');
\=> 'hi'
Return the piece of string until the last occurrence of the argument; return the whole string if not found. Example:
'hi.there.you'.substringUpToLast('.');
\=> 'hi.there'
Return the piece of string starting with the argument; empty string if not found. Example:
'hi.there'.substringFrom('.');
\=> 'there'
Return the piece from the last occurrence of the argument; empty string if not found. Example:
'hi.there.you'.substringFromLast('.');
\=> 'you'
Find out if the string contains the argument at any position. Example:
'abcde'.contains('bcd');
\=> true
Find out if the string contains the argument at any position, ignoring case. Example:
'aBcDe'.contains('bCd');
\=> true
Replace all occurrences of a string with the replacement. Example:
'pepitus'.replaceAll('p', 'c');
\=> 'cecitus'
Repeat the given string a few times. Example:
'ab'.repeat(3);
\=> 'ababab'
Capitalize a string: first letter upper case, rest as is. Example:
'hello'.capitalize();
\=> 'Hello'
Format a string using the same convention as util.format()
:
%s
represents a string value, %j
converts to JSON, and so on.
Example:
'Hi %s, %j'.format('a', {});
\=> 'Hi a, {}'
For objects some care must be taken before overwriting Object.prototype
:
otherwise it might break all code that does not check for hasOwnProperty().
See MDN help.
In this library all extensions are done using Object.defineProperty()
which does not pollute objects as the new properties are not enumerable.
Again, see MDN help.
Count the number of properties in an object. Does not count inherited properties: uses Object.keys(). Example:
{a: 'a'}.countProperties();
\=> 1
You can also pass a string or a function as a filter:
{hello: 'a'}.countProperties('ll');
\=> 1
{hello: 'a'}.countProperties(function(key) { return key.length == 5 });
\=> 1
Overwrite properties in the original with the given object. Example:
{a: 'a'}.overwriteWith({b: 'b'});
\=> {a: 'a', b: 'b'}
Note: properties which are undefined
are not overwritten;
all others (including null
) are. For instance:
{a: 'a'}.overwriteWith({b: undefined, c: null});
\=> {a: 'a', c: null}
Return a new object that includes properties of the object and the other object. Does not modify the original object. Example:
{a: 'a'}.concat({b: 'b'});
\=> {a: 'a', b: 'b'}
Call the callback for every value of the object.
Similar to array.forEach()
, the callback will receive three parameters:
value, key and the object itself.
Example:
{a: 1, b: 2}.forEach(function(value, key)
{
console.log(key + ': ' + value);
});
\=> a: 1
b: 2
Return a new object that only includes those properties of the object
that return true
for the given callback, i.e.:
callback(value) == true
.
Does not modify the original object.
Works also on arrays, equivalent to array.filter()
.
Example:
{a: 1, b: 2}.filterIn(function(value)
{
return value > 1;
});
\=> {b: 2}
Return a new object that only includes those properties of the object
that return false
for the given callback, i.e.:
callback(value) != true
.
Does not modify the original object.
Works also on arrays.
Example:
{a: 1, b: 2}.filterOut(function(value)
{
return value > 1;
});
\=> {a: 1}
The following array prototypes are provided.
Check if the array contains the given element. Example:
['a', 'b'].contains('a');
\=> true
Remove the element from the array if present, and return it. If not present, returns null. Example:
var array = ['a', 'b'];
array.remove('a');
\=> 'a'
array
\=> ['b']
Inherited from object.filterIn(checker)
, works also on arrays.
Identical to array.filter(checker)
.
Inherited from object.filterIn(checker)
, works also on arrays.
Similar to array.filter()
but reversed. Example:
['a', 'b', 'c1', 'c2'].filterOut(function(element)
{
return element.startsWith('c');
});
\=> ['a', 'b']
Returns a new sorted array of unique elements. Throws out null and undefined elements. Example:
['c', 'a', 'b', 'c', 'b'].unique();
\=> ['a', 'b', 'c']
Returns the first element of an array, or undefined for an empty array. Example:
['a', 'b', 'c'].first();
\=> 'a'
Returns the last element of an array, or undefined for an empty array. Example:
['a', 'b', 'c'].last();
\=> 'c'
Return an array with the object property values. If already an array, returns the unmodified array. Example:
Array.toArray({a: 1, b: 2});
\=> [1, 2]
Note: this function resides in the Array
global like Array.isArray()
,
instead of in individual arrays as the previous functions.
In versions up to 0.3.4 there were functions object.toArray()
and object.isArray()
,
but they were removed due to
incompatibilities with lodash.
There are math functions in Math
, in Number.prototype
, exported isNumber
and even as globals, e.g. parseInt()
.
By default parseInt() requires a radix (or base), or it will recreate the radix itself: if the string starts with a leading zero, then it interprets that you are parsing an octal number.
// unsafe parseInt()
parseInt('010');
\=> 8
This library replaces the global function with a safe version that uses radix 10 unless told otherwise. The last person that wanted to convert octal with leading zeroes is probably programming in C anyway. Example:
parseInt('010');
\=> 10
The function isNumber() is based on this StackOverflow answer: it checks if the parameter is a number. Examples:
var prototypes = require('prototypes');
prototypes.isNumber(5);
\=> true
prototypes.isNumber('hi');
\=> false
Logarithm in base 10. Example:
Math.log10(10);
\=> 1
Convert a number in degrees to radians. Example:
var n = 180;
n.toRad();
\=> 3.141592653589793
Prototypes used to enhance regular expressions (the RegExp prototype). Can also be used with the syntax /.../.
Returns a new regular expression which is always global. Example:
'pepitus'.replace(/p/.makeGlobal(), 'c');
\=> 'cecitus'
Thanks to my current employer MediaSmart Mobile for their permission to reuse some of the prototypes we have cooked together.
Thanks to William Wicks for letting me (even encouraging me to) plunder his extensions library.
This package is published under the MIT license. You can integrate it in any commercial, closed software and/or make changes to the code with complete liberty. If you send your changes back to the main repo we will be grateful, but it is by no means required.
FAQs
Some common prototypes for node.js: string.startsWith(), object.countProperties() and more. Facilities for functional programming with objects: object.forEach(), object.filter(). Functions are added safely using Object.defineProperty().
We found that prototypes demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Ransomware costs victims an estimated $30 billion per year and has gotten so out of control that global support for banning payments is gaining momentum.
Application Security
New SEC disclosure rules aim to enforce timely cyber incident reporting, but fear of job loss and inadequate resources lead to significant underreporting.
Security News
The Python Software Foundation has secured a 5-year sponsorship from Fastly that supports PSF's activities and events, most notably the security and reliability of the Python Package Index (PyPI).