Home

Awesome

utils NPM version Build Status

Fast, generic JavaScript/node.js utility functions.

Install with npm

$ npm i utils --save

TOC

<!-- toc -->

(Table of contents generated by verb)

<!-- tocstop -->

Usage

Utils grouped by collection

The top level export gives you an object with utils grouped into collections, like array, object, math, etc:

var utils = require('utils');
//=> {array: {flatten: [function], ...}, collection: {...}}

See example.md for an example of the utils object.

Get all utils on one object

If you want all utils on a single object (e.g. not grouped by collection):

// all utils are on the `_` property
var utils = require('utils')._;

Only get a specific collection

If you just want the string or object utils:

var string = require('utils').string;
var object = require('utils').object;

API

.after

Returns all of the items in an array after the specified index.

Params

Example

after(['a', 'b', 'c'], 1)
//=> ['c']

.arrayify

Cast the give value to an array.

Params

Example

arrayify('abc')
//=> ['abc']

arrayify(['abc'])
//=> ['abc']

.before

Returns all of the items in an array up to the specified number Opposite of <%= after() %.

Params

Example

before(['a', 'b', 'c'], 2)
//=> ['a', 'b']

.compact

Remove all falsey values from an array.

Params

Example

compact([null, a, undefined, 0, false, b, c, '']);
//=> [a, b, c]

.difference

Return the difference between the first array and additional arrays.

Params

Example

var a = ['a', 'b', 'c', 'd'];
var b = ['b', 'c'];

diff(a, b);
//=> ['a', 'd']

.each

Loop over each item in an array and call the given function on every element.

Params

Example

each(['a', 'b', 'c'], function (ele) {
  return ele + ele;
});
//=> ['aa', 'bb', 'cc']

each(['a', 'b', 'c'], function (ele, i) {
  return i + ele;
});
//=> ['0a', '1b', '2c']

.first

Returns the first item, or first n items of an array.

Params

Example

first(['a', 'b', 'c', 'd', 'e'], 2)
//=> ['a', 'b']

.flatten

Recursively flatten an array or arrays. Uses the fastest implementation of array flatten for node.js

Params

Example

flatten(['a', ['b', ['c']], 'd', ['e']]);
//=> ['a', 'b', 'c', 'd', 'e']

.forEach

Loop over each item in an array and call the given function on every element.

Params

Example

forEach(['a', 'b', 'c'], function (ele) {
  return ele + ele;
});
//=> ['aa', 'bb', 'cc']

forEach(['a', 'b', 'c'], function (ele, i) {
  return i + ele;
});
//=> ['0a', '1b', '2c']

.isArray

Returns true if the given value is an array.

Params

Example

isArray(1);
//=> 'false'

isArray([1]);
//=> 'true'

.last

Returns the last item, or last n items of an array.

Params

Example

last(['a', 'b', 'c', 'd', 'e'], 2)
//=> ['d', 'e']

.map

Returns a new array with the results of calling the given function on every element in the array. This is a faster, node.js focused alternative to JavaScript's native array map.

Params

Example

map(['a', 'b', 'c'], function (ele) {
  return ele + ele;
});
//=> ['aa', 'bb', 'cc']

map(['a', 'b', 'c'], function (ele, i) {
  return i + ele;
});
//=> ['0a', '1b', '2c']

.slice

Alternative to JavaScript's native array-slice method. Slices array from the start index up to but not including the end index.

Params

Example

var arr = ['a', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

slice(arr, 3, 6);
//=> ['e', 'f', 'g']

.union

Return an array free of duplicate values. Fastest ES5 implementation.

Params

Example

union(['a', 'b', 'c', 'c']);
//=> ['a', 'b', 'c']

.unique

Return an array free of duplicate values. Fastest ES5 implementation.

Params

Example

unique(['a', 'b', 'c', 'c']);
//=> ['a', 'b', 'c']

.any

Returns true if value exists in the given string, array or object. See [any] for documentation.

Params

.contains

Return true if collection contains value

Params

.tryRead

Try to read the given filepath, fail silently and return null when a file doesn't exist. Slightly faster than using fs.existsSync.

Params

.tryReaddir

Try to read the given directory. Wraps fs.readdirSync() with a try/catch, so it fails silently instead of throwing when the directory doesn't exist.

Params

.tryRequire

Try to require the given file, returning null if not successful instead of throwing an error.

Params

.identity

Returns the first argument passed to the function.

.noop

A "no-operation" function. Returns undefined regardless of the arguments it receives.

.partialRight

Partially applies arguments that will be appended to those provided to the returned function.

Params

Example

function fullname(first, last) {
  return first + ' ' + last;
}

var name = partialRight(fn, 'Woodward');
name('Brian');
//=> 'Brian Woodward'

.hasValues

Returns true if any value exists, false if empty. Works for booleans, functions, numbers, strings, nulls, objects and arrays.

Params

Example

hasValues('a');
//=> true

hasValues('');
//=> false

hasValues(1);
//=> true

hasValues({a: 'a'}});
//=> true

hasValues({}});
//=> false

hasValues(['a']);
//=> true

.isEmpty

Returns true if the given value is empty, false if any value exists. Works for booleans, functions, numbers, strings, nulls, objects and arrays.

Params

Example

isEmpty('a');
//=> false

isEmpty('');
//=> true

isEmpty(1);
//=> false

isEmpty({a: 'a'});
//=> false

isEmpty({});
//=> true

isEmpty(['a']);
//=> false

.isObject

Return true if the given value is an object with keys.

Params

Example

isObject(['a', 'b', 'c'])
//=> 'false'

isObject({a: 'b'})
//=> 'true'

.isPlainObject

Return true if the given value is an object with keys.

Params

Example

isPlainObject(Object.create({}));
//=> true
isPlainObject(Object.create(Object.prototype));
//=> true
isPlainObject({foo: 'bar'});
//=> true
isPlainObject({});
//=> true

.sum

Returns the sum of all numbers in the given array.

Params

Example

sum([1, 2, 3, 4, 5])
//=> '15'

.defaults

Extend object with properties of other objects

Params

.extend

Extend o with properties of other objects.

Params

.functions

Returns a copy of the given obj filtered to have only enumerable properties that have function values.

Params

Example

functions({a: 'b', c: function() {}});
//=> {c: function() {}}

.hasOwn

Return true if key is an own, enumerable property of the given obj.

Params

Example

hasOwn(obj, key);

.keys

Return an array of keys for the given obj. Uses Object.keys when available, otherwise falls back on forOwn.

Params

mapValues

Returns new object where each value is the result of calling the a callback function.

Params

.merge

Recursively combine the properties of o with the properties of other objects.

Params

.methods

Returns a list of all enumerable properties of obj that have function values

Params

.reduce

Reduces an object to a value that is the accumulated result of running each property in the object through a callback.

Params

Example

var a = {a: 'foo', b: 'bar', c: 'baz'};

reduce(a, function (acc, value, key, obj) {
  // `acc`- the initial value (or value from the previous callback call),
  // `value`- the of the current property,
  // `key`- the of the current property, and
  // `obj` - original object

  acc[key] = value.toUpperCase();
  return acc;
}, {});

//=> {a: 'FOO', b: 'BAR', c: 'BAZ'};

.camelcase

camelCase the characters in string.

Params

Example

camelcase("foo bar baz");
//=> 'fooBarBaz'

.centerAlign

Center align the characters in a string using non-breaking spaces.

Params

Example

centerAlign("abc");

.chop

Like trim, but removes both extraneous whitespace and non-word characters from the beginning and end of a string.

Params

Example

chop("_ABC_");
//=> 'ABC'

chop("-ABC-");
//=> 'ABC'

chop(" ABC ");
//=> 'ABC'

.count

Count the number of occurrances of a substring within a string.

Params

Example

count("abcabcabc", "a");
//=> '3'

.dashcase

dash-case the characters in string. This is similar to [slugify], but [slugify] makes the string compatible to be used as a URL slug.

Params

Example

dashcase("a b.c d_e");
//=> 'a-b-c-d-e'

.dotcase

dot.case the characters in string.

Params

Example

dotcase("a-b-c d_e");
//=> 'a.b.c.d.e'

.ellipsis

Truncate a string to the specified length, and append it with an elipsis, .

Params

Example

ellipsis("<span>foo bar baz</span>", 7);
//=> 'foo bar…'

.hyphenate

Replace spaces in a string with hyphens. This

Params

Example

hyphenate("a b c");
//=> 'a-b-c'

.isString

Returns true if the value is a string.

Params

Example

isString('abc');
//=> 'true'

isString(null);
//=> 'false'

.pascalcase

PascalCase the characters in string.

Params

Example

pascalcase("foo bar baz");
//=> 'FooBarBaz'

.pathcase

path/case the characters in string.

Params

Example

pathcase("a-b-c d_e");
//=> 'a/b/c/d/e'

.replace

Replace occurrences of a with b.

Params

Example

replace("abcabc", /a/, "z");
//=> 'zbczbc'

.reverse

Reverse the characters in a string.

Params

Example

reverse("abc");
//=> 'cba'

.rightAlign

Right align the characters in a string using non-breaking spaces.

Params

Example

rightAlign(str);

.sentencecase

Sentence-case the characters in string.

Params

Example

sentencecase("foo bar baz.");
//=> 'Foo bar baz.'

.snakecase

snake_case the characters in string.

Params

Example

snakecase("a-b-c d_e");
//=> 'a_b_c_d_e'

.truncate

Truncate a string by removing all HTML tags and limiting the result to the specified length.

Params

Example

truncate("<span>foo bar baz</span>", 7);
//=> 'foo bar'

.wordwrap

Wrap words to a specified width using [word-wrap].

Params

Example

wordwrap("a b c d e f", {width: 5, newline: '<br>  '});
//=> '  a b c <br>  d e f'

Code coverage

Please help improve code coverage by adding unit tests.

-----------------------|----------|----------|----------|----------|----------------|
File                   |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
-----------------------|----------|----------|----------|----------|----------------|
 utils/                |      100 |      100 |      100 |      100 |                |
  index.js             |      100 |      100 |      100 |      100 |                |
 utils/lib/            |      100 |      100 |      100 |      100 |                |
  index.js             |      100 |      100 |      100 |      100 |                |
 utils/lib/array/      |    91.75 |    83.33 |      100 |    92.55 |                |
  after.js             |      100 |       75 |      100 |      100 |                |
  arrayify.js          |      100 |      100 |      100 |      100 |                |
  before.js            |      100 |       75 |      100 |      100 |                |
  compact.js           |      100 |      100 |      100 |      100 |                |
  difference.js        |      100 |      100 |      100 |      100 |                |
  each.js              |      100 |      100 |      100 |      100 |                |
  first.js             |    88.89 |    83.33 |      100 |    88.24 |          27,46 |
  flatten.js           |      100 |      100 |      100 |      100 |                |
  forEach.js           |      100 |      100 |      100 |      100 |                |
  index.js             |      100 |      100 |      100 |      100 |                |
  indexOf.js           |    76.92 |       70 |      100 |    83.33 |          23,40 |
  isArray.js           |      100 |      100 |      100 |      100 |                |
  last.js              |    88.89 |    83.33 |      100 |    88.24 |          27,46 |
  map.js               |      100 |      100 |      100 |      100 |                |
  slice.js             |      100 |      100 |      100 |      100 |                |
  sort.js              |    90.91 |     87.5 |      100 |    90.91 |             27 |
  union.js             |      100 |      100 |      100 |      100 |                |
  unique.js            |      100 |      100 |      100 |      100 |                |
 utils/lib/collection/ |    55.56 |        0 |        0 |    55.56 |                |
  any.js               |      100 |      100 |      100 |      100 |                |
  contains.js          |    42.86 |        0 |        0 |    42.86 |    18,19,21,22 |
  index.js             |      100 |      100 |      100 |      100 |                |
 utils/lib/fs/         |    68.75 |      100 |    66.67 |    68.75 |                |
  index.js             |      100 |      100 |      100 |      100 |                |
  tryRead.js           |       40 |      100 |        0 |       40 |       16,17,19 |
  tryReaddir.js        |       80 |      100 |      100 |       80 |             20 |
  tryRequire.js        |       80 |      100 |      100 |       80 |             19 |
 utils/lib/function/   |    36.36 |        0 |        0 |    36.36 |                |
  identity.js          |       50 |      100 |        0 |       50 |             12 |
  index.js             |      100 |      100 |      100 |      100 |                |
  noop.js              |       50 |      100 |        0 |       50 |             13 |
  partialRight.js      |    16.67 |        0 |        0 |    16.67 | 26,27,28,29,30 |
 utils/lib/lang/       |      100 |      100 |      100 |      100 |                |
  hasValues.js         |      100 |      100 |      100 |      100 |                |
  index.js             |      100 |      100 |      100 |      100 |                |
  isEmpty.js           |      100 |      100 |      100 |      100 |                |
  isObject.js          |      100 |      100 |      100 |      100 |                |
  isPlainObject.js     |      100 |      100 |      100 |      100 |                |
  typeOf.js            |      100 |      100 |      100 |      100 |                |
 utils/lib/math/       |      100 |      100 |      100 |      100 |                |
  index.js             |      100 |      100 |      100 |      100 |                |
  sum.js               |      100 |      100 |      100 |      100 |                |
 utils/lib/object/     |    62.77 |    46.15 |    17.65 |    61.96 |                |
  defaults.js          |      100 |      100 |      100 |      100 |                |
  extend.js            |      100 |    83.33 |      100 |      100 |                |
  filter.js            |      100 |      100 |      100 |      100 |                |
  forIn.js             |      100 |      100 |      100 |      100 |                |
  forOwn.js            |      100 |      100 |      100 |      100 |                |
  functions.js         |    28.57 |        0 |        0 |    28.57 | 21,23,24,25,29 |
  hasOwn.js            |      100 |      100 |      100 |      100 |                |
  index.js             |      100 |      100 |      100 |      100 |                |
  keys.js              |    33.33 |       50 |        0 |    33.33 |    16,17,18,20 |
  mapValues.js         |     37.5 |      100 |        0 |     37.5 | 18,19,21,22,25 |
  merge.js             |      100 |       75 |      100 |      100 |                |
  methods.js           |    28.57 |        0 |        0 |    28.57 | 16,18,19,20,24 |
  omit.js              |      100 |      100 |      100 |      100 |                |
  pick.js              |      100 |      100 |      100 |      100 |                |
  pluck.js             |       75 |      100 |        0 |       75 |             17 |
  prop.js              |    33.33 |      100 |        0 |    33.33 |            4,5 |
  reduce.js            |      100 |      100 |      100 |      100 |                |
  result.js            |       25 |        0 |        0 |       25 | 6,7,8,10,11,13 |
  some.js              |       30 |        0 |        0 |       30 |... 11,12,13,16 |
 utils/lib/string/     |    99.28 |    96.77 |       96 |     99.1 |                |
  camelcase.js         |      100 |      100 |      100 |      100 |                |
  centerAlign.js       |      100 |      100 |      100 |      100 |                |
  chop.js              |      100 |      100 |      100 |      100 |                |
  count.js             |      100 |      100 |      100 |      100 |                |
  dashcase.js          |      100 |      100 |      100 |      100 |                |
  dotcase.js           |      100 |      100 |      100 |      100 |                |
  ellipsis.js          |      100 |      100 |      100 |      100 |                |
  hyphenate.js         |      100 |      100 |      100 |      100 |                |
  index.js             |      100 |      100 |      100 |      100 |                |
  isString.js          |      100 |      100 |      100 |      100 |                |
  pascalcase.js        |      100 |      100 |      100 |      100 |                |
  pathcase.js          |      100 |      100 |      100 |      100 |                |
  replace.js           |      100 |      100 |      100 |      100 |                |
  reverse.js           |      100 |      100 |      100 |      100 |                |
  rightAlign.js        |      100 |      100 |      100 |      100 |                |
  sentencecase.js      |      100 |      100 |      100 |      100 |                |
  slugify.js           |      100 |      100 |      100 |      100 |                |
  snakecase.js         |      100 |      100 |      100 |      100 |                |
  toString.js          |       50 |        0 |        0 |       50 |             10 |
  truncate.js          |      100 |      100 |      100 |      100 |                |
  wordwrap.js          |      100 |      100 |      100 |      100 |                |
-----------------------|----------|----------|----------|----------|----------------|
All files              |    84.54 |    80.52 |    67.16 |    83.43 |                |
-----------------------|----------|----------|----------|----------|----------------|

Running tests

Install dev dependencies:

$ npm i -d && npm test

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Adding utils

If you want to do a PR to add a util, please read the following first:

Adding external modules as dependencies

Updating the docs

Do not edit the readme manually since verbis used to generate documentation.

Running verb

Install dev dependencies, then run verb:

$ npm install -d && verb

About

Why another utils lib?

Project goals

Related projects

This project depends on these great libraries. If you don't need a full utility belt for your project, any of these can be used by themselves:

Author

Jon Schlinkert

License

Copyright © 2015 Jon Schlinkert Released under the MIT license.


This file was generated by verb-cli on September 23, 2015.