Thanks to visit codestin.com
Credit goes to github.com

Skip to content
peter edited this page Oct 3, 2017 · 16 revisions

1. Overview

busyman is a lightweight and lodash-like JS utility library that provides commonly used functions for your convenience.


2. Installation

$ npm install busyman --save


3. Usage

var _ = require('busyman');

console.log(_.isArray('hello'));    // false

4. APIs

_.isNull(value)

Checks if a value is null.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is null, otherwise false.

Examples:

var aUndef;

_.isNull(null);     // true
_.isNull(aUndef);   // false
_.isNull(3);        // false



_.isNil(value)

Checks if a value is null or undefined.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is null or undefined, otherwise false.

Examples:

var aUndef;

_.isNil(null);      // true
_.isNil(aUndef);    // true
_.isNil(3);         // false
_.isNil([]);        // false



_.isUndefined(value)

Checks if a value is undefined.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is undefined, otherwise false.

Examples:

var aUndef;

_.isUndefined();        // true
_.isUndefined(aUndef);  // true
_.isUndefined(6);       // false



_.isNaN(value)

Checks if a value is NaN. This method is based on the global isNaN.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is NaN, otherwise false.

Examples:

// These examples are from MDN document
_.isNaN(NaN);       // true
_.isNaN(undefined); // true
_.isNaN({});        // true
_.
_.isNaN(true);      // false
_.isNaN(null);      // false
_.isNaN(37);        // false

// strings
_.isNaN("37");      // false
_.isNaN("37.37");   // false
_.isNaN("123ABC");  // true
_.isNaN("");        // false
_.isNaN(" ");       // false

// dates
_.isNaN(new Date());            // false
_.isNaN(new Date().toString()); // true

// This is a false positive and the reason why isNaN is not entirely reliable
_.isNaN("blabla");  // true: "blabla" is converted to a number. 
                    // Parsing this as a number fails and returns NaN



_.isArray(value)

Checks if a value is an array. This method is based on Array.isArray.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is, otherwise false.

Examples:

_.isArray([ 1 ]);       // true
_.isArray({ x: 1 });    // false



_.isObject(value)

Checks if a value is an object. A null is considered not an object. An array is considered as an object as usual.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is an object, otherwise false.

Examples:

var anObject = { x: 1 },
    anArray = [ 1, 2 ],
    aNull = null,
    notAnObject = 8;

_.isObject({ x: 1 });   // true
_.isObject([ 1, 2 ]);   // true
_.isObject(null);       // false
_.isObject(8);          // false



_.isPlainObject(value)

Checks if a value is a plain object. A null is not an plain object. An array is not an plain object. An object created from a constructo other than Object constructor is not an plain object.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is a plain object, otherwise false.

Examples:

function Foo() {}           // Foo constructor

_.isPlainObject({ x: 1 });  // true
_.isPlainObject([ 1, 2 ]);  // false
_.isPlainObject(null);      // false
_.isPlainObject(8);         // false
_.isPlainObject(new Foo()); // false



_.isBuffer(value)

Checks if a value is a Buffer. This method is based on node.js Buffer.isBuffer.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is a buffer, otherwise false.

Examples:

_.isBuffer(new Buffer([ 1, 2, 3 ]));    // true
_.isBuffer([ 1, 2 ]);                   // false



_.isBoolean(value)

Checks if a value is a bool.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is a bool, otherwise false.

Examples:

_.isBoolean(false); // true
_.isBoolean(18);    // false



_.isNumber(value)

Checks if a value is a number.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is a number, otherwise false.

Examples:

_.isNumber(3);          // true
_.isNumber('18');       // false
_.isNumber('hello');    // false



_.isString(value)

Checks if a value is a string.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is a string, otherwise false.

Examples:

_.isString('hello');    // true
_.isString(6);          // false



_.isInteger(value)

Checks if a value is an integer. This method is based on Number.isInteger.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is an interger, otherwise false.

Examples:

_.isInteger(12);    // true
_.isInteger(1.36);  // false
_.isInteger('hi');  // false
_.isInteger('18');  // false
_.isInteger({});    // false



_.isFunction(value)

Checks if a value is a function.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is a function, otherwise false.

Examples:

_.isFunction(function () {});   // true
_.isFunction(6);                // false



_.parseInt(string[, radix])

Parses a string to an integer with the specified radix. This method is based on the global parseInt.

Arguments:

  • (String): The string to parse.

Returns:

  • (Number): The parsed numeric value, or NaN if parsing fails.

Examples:

_.parseInt(" 0xF", 16);     // 15
_.parseInt("17", 8));       // 15
_.parseInt("-F", 16));      // -15
_.parseInt(-15.1, 10));     // -15
_.parseInt("-1111", 2));    // -15
_.parseInt("hello", 16);    // NaN
_.parseInt("546", 2);       // NaN
_.parseInt([], 16);         // NaN
_.parseInt({}, 16);         // NaN
_.parseInt(true, 16);       // NaN



_.startsWith(string, target[, position])

Checks if a string starts with the given target string.

Arguments:

  1. string (String): The string to search.
  2. target (String | RegExp): The string to search for.
  3. position (Number): The position to search from.

Returns:

  • (Boolean): Returns true if string starts with target, else false.

Examples:

_.startsWith('abc', 'a');       // true
_.startsWith('abc', 'b');       // false
_.startsWith('abc', 'b', 1);    // true



_.endsWith(string, target[, position])

Checks if the string ends with the given target string.

Arguments:

  1. string (String): The string to search.
  2. target (String): The string to search for.
  3. position (Number): The position to search up to.

Returns:

  • (Boolean): Returns true if string ends with target, else false.

Examples:

_.endsWith('abc', 'c');     // true
_.endsWith('abc', 'b');     // false
_.endsWith('abc', 'b', 2);  // true



_.split(string, separator[, limit])

Splits a string, according to the separator, into an array of the split strings.

Arguments:

  1. string (String): The string to split.
  2. separator (String | RegExp): The separator pattern to split by.
  3. limit (Number): The length to truncate results to.

Returns:

  • (Array): Returns the string segments.

Examples:

_.split('abcde', 'c');      // [ 'ab', 'de' ]
_.split('abcde', /[bd]/);   // [ 'a', 'c', 'e' ]
_.split('abcde', '', 3);    // [ 'a', 'b', 'c' ]



_.replace(string, pattern, replacement)

Replaces matches for pattern in string with replacement.

Arguments:

  1. string (String): The string to modify.
  2. pattern (String | RegExp): The pattern to replace.
  3. replacement (String | Function): The match replacement.

Returns:

  • (String): Returns the modified string.

Examples:

_.replace('abcde', 'c', ' ');       // 'ab de'
_.replace('abcde', 'cde', '123');   // 'ab123'
_.replace('abcde', /[bd]/g, '-');   // 'a-c-e'



_.camelCase(string)

Converts a string into camel case.

Arguments:

  1. string (String): The string to convert.

Returns:

  • (String): Returns the camel cased string.

Examples:

_.camelCase('24 hour');     // '24Hour'
_.camelCase('HELLO-WORLD'); // 'helloWorld'
_.camelCase('__FOO_BAR__'); // 'fooBar'



_.toLower(string)

Converts a string into lower case.

Arguments:

  1. string (String): The string to convert.

Returns:

  • (String): Returns the lower cased string.

Examples:

_.toLower('ABCDE');         // 'abcde'
_.toLower('24_HOUR');       // '24_hour'
_.toLower('--FOO-BAR--');   // '--foo-bar--'



_.toUpper(string)

Converts a string into upper case.

Arguments:

  1. string (String): The string to convert.

Returns:

  • (String): Returns the upper cased string.

Examples:

_.toUpper('abcde');         // 'ABCDE'
_.toUpper('24_hour');       // '24_HOUR'
_.toUpper('--foo-bar--');   // '--FOO-BAR--'



_.lowerCase(string)

Converts a string, as space separated words, to lower case.

Arguments:

  1. string (String): The string to convert.

Returns:

  • (String): Returns the lower cased string.

Examples:

_.lowerCase('HELLO');       // 'hello'
_.lowerCase('HELLO-WORLD'); // 'hello world'



_.upperCase(string)

Converts a string, as space separated words, to upper case.

Arguments:

  1. string (String): The string to convert.

Returns:

  • (String): Returns the upper cased string.

Examples:

_.upperCase('hello');           // 'HELLO'
_.upperCase('hello-world');     // 'HELLO WORLD'



_.lowerFirst(string)

Converts the first character of a string to lower case.

Arguments:

  1. string (String): The string to convert.

Returns:

  • (String): Returns the converted string.

Examples:

_.lowerFirst('HELLO');          // 'hELLO'
_.lowerFirst('HELLO-WORLD');    // 'hELLO-WORLD'



_.upperFirst(string)

Converts the first character of a string to upper case.

Arguments:

  1. string (String): The string to convert.

Returns:

  • (String): Returns the converted string.

Examples:

_.upperFirst('hello');          // 'Hello'
_.upperFirst('hello-world');    // 'Hello-world'



_.has(object, path)

Checks if the path is the direct property in the object.

Arguments:

  1. object (Object): The object to query.
  2. path (String | Array): Path to be checked.

Returns:

  • (Boolean): Returns true if path exists, otherwise false.

Examples:

var object = {
    x: {
        y: [ { z: 5 } ]
    }
};

_.has(object, 'x.y[0].z');              // true
_.has(object, ['x', 'y', '0', 'z']);    // true
_.has(object, 'x.y.z');                 // 'false



_.includes(collection, value)

Checks if the value is in collection.

Arguments:

  1. collection (Object | Array | String): The collection to query.
  2. value (Depends): The value to search for.

Returns:

  • (Boolean): Returns true if value is found, else false.

Examples:

var obj = { 'user': 'fred', 'age': 40 },
    arr = [ 1, 2, 3 ],
    str = 'pebbles';

_.includes(obj, 'fred');     // true
_.includes(obj, 'freddy');   // false

_.includes(arr, 2);          // true
_.includes(arr, 4);          // false

_.includes(str, 'eb');       // true
_.includes(str, 'ese');      // false



_.every(collection, predicate)

Checks if every value in the collection pass the predicate test.

Arguments:

  1. collection (Object | Array): The collection to query.
  2. predicate (Function): function (value, key|index, collection) { }, the function invoked per iteration.
    • value: The current value being processed in the collection.
    • key|index: The key or index of the current property being processed in the collection.
    • collection: The original collection.

Returns:

  • (Boolean): Returns true if every value passes the test, else returns false.

Examples:

var obj = { 'user': 'fred', 'age': 40 },
    arr = [ 1, 2, 3 ];

_.every(obj, function (v) {
    return v === 'fred';
});     // false

_.every(arr, function (v) {
    return v === 2;
});     // false

_.every(arr, _.isNumber);   // true



_.keys(object)

Creates an array contains all own enumerable property names of a given object. This method is based on Object.keys.

Arguments:

  1. object (Object): The object to query.

Returns:

  • (Array): Returns the array of all property names.

Examples:

function Foo() {
    this.x = 0;
    this.y = 1;
}

Foo.prototype.z = 2;

_.keys(new Foo);
// [ 'x', 'y' ]  (iteration order is not guaranteed)

_.keys([ 1, 2, 3, 4, 5 ]);
// [ '0', '1', '2', '3', '4' ]



_.values(object)

Creates an array contains all own enumerable property values of a given object.

Arguments:

  1. object (Object): The object to query.

Returns:

  • (Array): Returns the array of all property values.

Examples:

function Foo() {
    this.x = 0;
    this.y = 1;
}

Foo.prototype.z = 2;

_.values(new Foo);
// [ 0, 1 ]  (iteration order is not guaranteed)

_.values([ 1, 2, 3, 4, 5 ]);
// [ 1, 2, 3, 4, 5 ]

_.values('hey');
// [ 'h', 'e', 'y' ]



_.size(collection)

Obtains size of the collection.

Arguments:

  1. collection (Object | Array | String): The collection to query.

Returns:

  • (Number): Returns the collection size.

Examples:

var obj = { 'user': 'fred', 'age': 40 },
    arr = [ 1, 2, 3 ],
    str = 'pebbles';

_.size(obj);   // 2
_.size(arr);   // 3
_.size(str);   // 7



_.assign(object[, sources1[, sources2[, ...[, sourcesN]]]])

Copy the values of all enumerable own properties from one or more source objects to a destination object. It will return the destination object. Source objects in the arguments are applied from left to right. This method is based on Object.assign.

Arguments:

  1. object (Object): The destination object.
  2. sourcesN (Object): The source objects.

Returns:

  • (Object): Destination object

Examples:

var result;

var function A() {
    this.b = 1;
}

var function B() {
    this.d = 3;
}

A.prototype.c = 2;
B.prototype.e = 4;

result = _.assign({ a: 0 }, new A(), new B());
// { a: 0, b: 1, d: 3 }



_.merge(object[, sources1[, sources2[, ...[, sourcesN]]]])

Merges all source objects into the destination object.

Arguments:

  1. object (Object): The destination object.
  2. sourceN (Object): The source objects.

Returns:

  • (Object): The destination object.

Examples:

var originObj = {
        data: [ { user: 'arya' }, { user: 'robb' } ]
    },
    sourceObj1 = {
        data: [ { age: 19 }, { age: 25 } ]
    };

_.merge(originObj, sourceObj1);
// [ { user: 'arya', age: 19 }, { user: 'robb', age: 25 } ]



_.omit(object, props)

Create an object with properties that are not omitted in object.

Arguments:

  1. object (Object): The source object.
  2. props (String | Array): Properties to be omitted.

Returns:

  • (Object): New object with properities not omitted.

Examples:

var object = {
    x: 0,
    y: '1',
    z: 2
};

_.omit(object, 'x');        // { y: '1', z: 2 }
_.omit(object, ['y', 'z']); // { x: 0 }



_.pick(object, props)

Create an object with properties that are picked from the object.

Arguments:

  1. object (Object): The source object.
  2. props (String | Array): Properties to be picked.

Returns:

  • (Object): New object with picked properities.

Examples:

var object = {
    x: 0,
    y: '1',
    z: 2
};

_.pick(object, 'x');            // { x: 0 }
_.pick(object, [ 'y', 'z' ]);   // { y: '1', z: 2 }



_.get(object, path[, defaultValue])

Gets the value at the specified path from an object.

Arguments:

  1. object (Object): The object to query.
  2. path (Array | String): The path refers to an object property.
  3. defaultValue (Depends): If value of specified path not found, return defaultValue.

Returns:

  • (Depends): The value at the specified path.

Examples:

var object = {
    x: {
        y: [ { z: 5 } ]
    }
};

_.get(object, 'x.y[0].z');              // 5
_.get(object, ['x', 'y', '0', 'z']);    // 5
_.get(object, 'x.y.z', 'foo');          // returns default value 'foo' when target not found



_.set(object, path, value)

Set property to the new value at the given path.

Arguments:

  1. object (object): The object to be set.
  2. path (String | Array): The path to the property.
  3. value (Depends): The value to set.

Returns:

  • (Object): object

Examples:

var object = {
    x: {
        y: [ { z: 5 } ]
    }
};

_.set(object, 'x.y[0].z'), 'hello');
// {
//     x: {
//         y: [ { z: 'hello' } ]
//     }
// }



_.unset(object, path)

Delete property from the object at the given path.

Arguments:

  1. object (object): The object to be unset.
  2. path (String | Array): The path to the property.

Returns:

  • (Boolean): true of unset, else false.

Examples:

var object = {
    x: {
        y: [ { z: 5, m: 'hi' } ]
    }
};

_.unset(object, 'x.y[0].z'));   // true
console.log(object);
// {
//     x: {
//         y: [ { m: 'hi' } ]
//     }
// }



_.find(collection, predicate)

Iterates over elements in collection. This method returns the first element of predicate returns truthy for.

Arguments:

  1. collection (Array | Object): The collection to be iterated.
  2. predicate (Function): function (value, key|index, collection) { }, the function invoked per iteration.
    • value: The current value being processed in the collection.
    • key|index: The key or index of the current property being processed in the collection.
    • collection: The original collection.

Returns:

  • (Depends): The first matched element.

Examples:

var users = [
        { 'user': 'arya',  'age': 19, 'active': true },
        { 'user': 'robb',  'age': 25, 'active': false },
        { 'user': 'sansa', 'age': 22, 'active': true }
    ],
    result;

result = _.find(users, function (user) {
    return user.age > 20; 
});

console.log(result);    // { 'user': 'robb', 'age': 25, 'active': false }



_.filter(collection, predicate)

Iterates over elements in collection. The method returns an array which contains all elements of predicate returns truthy for.

Arguments:

  1. collection (Array | Object): The collection to be iterated.
  2. predicate (Function): function (value, key|index, collection) { }, the function invoked per iteration.
    • value: The current value being processed in the collection.
    • key|index: The key or index of the current property being processed in the collection.
    • collection: The original collection.

Returns:

  • (Array): Returns the new filtered array.

Examples:

var users = [
        { 'user': 'arya',  'age': 19, 'active': true },
        { 'user': 'robb',  'age': 25, 'active': false },
        { 'user': 'sansa', 'age': 22, 'active': true }
    ],
    result;

result = _.filter(users, function (user) {
    return user.active === true;
});

console.log(result);
// [
//     { 'user': 'arya',  'age': 19, 'active': true },
//     { 'user': 'sansa', 'age': 22, 'active': true }
// ]



_.forOwn(object, iteratee)

Iterates all own enumerable properties of the object, and invokes iteratee with each property. Iteratee function may exit iteration early by explicitly returning false.

Arguments:

  1. object (Object): The object to be iterated.
  2. iteratee (Function): function (value, key|index, object) { }, the function invoked per iteration.
    • value: The current value being processed in the object.
    • key|index: The key of the current property being processed in the object.
    • object: The original object.

Returns:

  • (none)

Examples:

var keys = [],
    vals = [];

function Foo() {
    this.x = 0;
    this.y = 1;
}

Foo.prototype.z = 2;

_.forOwn(new Foo, function(val, key) {
    keys.push(key);
    vals.push(val);
});

console.log(keys);
// [ 'x', 'y' ]

console.log(vals);
// [ 0, 1 ]



_.some(collection, predicate)

Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate returns truthy.

Arguments:

  1. collection (Array|Object): The collection to iterate over.
  2. predicate (Function): function (value, key, collection) { }, the function invoked per iteration.
    • value: The current value being processed in the collection.
    • key: The key or index of the current element being processed in the collection.
    • collection: The original collection.

Returns:

  • (Boolean): Returns true if any element passes the predicate check, else false.

Examples:

_.some([ 1, 2, 3, 4, 5 ], function (val) {
    return val % 2 === 0;
}); // true

_.some([ 1, 3, 5 ], function (val) {
    return val % 2 === 0;
}); // false



_.findIndex(array, predicate[, thisArg])

This method returns the index of the first element that makes predicate return truthy. This method is based on Array.prototype.findIndex.

Arguments:

  1. array (Array): The array to search.
  2. predicate (Function): function (value, index, array) { }, the function invoked per iteration.
    • value: The current value being processed in the array.
    • index: The index of the current value being processed in the array.
    • array: The original array.
  3. thisArg (Depends): Optional. Object to use as this when executing callback.

Returns:

  • (Number): Returns the index of the found element, else -1.

Examples:

var array = [ 1, 2, 3, 1, 2, 3 ];

_.findIndex(array, function (value, index, array) {
    return value > 2;
}); // 2

_.findIndex(array, function (value, index, array) {
    return value > 4;
}); // -1



_.indexOf(array, value[, fromIndex])

Gets the index at which a given value been firstly found in the array. This method is based on Array.prototype.find.

Arguments:

  1. array (Array): The array to search.
  2. value (String | Number): The value to search for.
  3. fromIndex (Number): The index to search from. Default is 0.

Returns:

  • (Number): Returns the index of the matched element, else -1.

Examples:

var array = [ 1, 2, 3, 1, 2, 3 ];

_.indexOf(array, 3);    // 2
_.indexOf(array, 3, 2); // 5



_.concat(array, value1[, value2[, ...[, valueN]]])

Creates a new array concatenating array with any additional arrays and/or values. This method is based on Array.prototype.concat.

Arguments:

  1. array (Array): The array to concatenate.
  2. valueN (Depends): The values to concatenate.

Returns:

  • (Array): Returns the new concatenated array.

Examples:

var array = [ 1 ];
var other = _.concat(array, 2, [ 3 ], [ [ 4 ] ]);

console.log(other);     // [ 1, 2, 3, [ 4 ] ]
console.log(array);     // [ 1 ]



_.join(array[, separator])

Converts all elements in array into a string separated by separator. This method is based on Array.prototype.join.

Arguments:

  1. array (Array): The array to convert.
  2. separator (String): Specifies a string to separate each element of the array. Default is ','.

Returns:

  • (String): Returns the joined string.

Examples:

_.join([ 'a', 'b', 'c' ]);       // 'a,b,c'
_.join([ 'a', 'b', 'c' ], '-');  // 'a-b-c'



_.slice(array[, start[, end]])

Creates a slice of shallow copied array from parts of the given array. This method is based on Array.prototype.slice.

Arguments:

  1. array (Array): The array to slice.
  2. start (Number): The start position. Default is 0.
  3. end (Number): The end position. Default is array.length.

Returns:

  • (Array): Returns the slice of array.

Examples:

var array = [ 1, 2, 3 ];

_.slice(array, 1);      // [ 2, 3 ]
_.slice(array, 1, 2);   // [ 2 ]



_.last(array)

Gets the last element of array.

Arguments:

  1. array (Array): The array to query.

Returns:

  • (Depends): Returns the last element of array.

Examples:

_.last([ 'a', 'b', 'c' ]);    // 'c'



_.pull(array, value1[, value2[, ...[, valueN]]])

Removes all given values from array.

Arguments:

  1. array (Array): The array to modify.
  2. valueN (String | Number): The values to remove.

Returns:

  • (Array): Returns the pulled array.

Examples:

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

_.pull(array, 'a', 'c');    // [ 'b', 'b' ]



_.take(array)

Creates a slice of array with n elements taken from the beginning.

Arguments:

  1. array (Array): The array to query.
  2. n (Number): The number of elements to take.

Returns:

  • (Array): Returns the slice of array.

Examples:

var array = [ 1, 2, 3 ];

_.take(array, 2);   // [ 1, 2 ]



_.drop(array, n)

Creates a slice of array with n elements dropped from the beginning.

Arguments:

  1. array (Array): The array to query.
  2. n (Number): The number of elements to drop. Default is 0.

Returns:

  • (Array): Returns the slice of array.

Examples:

var array = [ 1, 2, 3, 4, 5, 6 ];

_.drop(array);      // [ 1, 2, 3, 4, 5, 6 ]
_.drop(array, 3);   // [ 4, 5, 6 ]
_.drop(array, 6);   // []



_.dropRight(array, n)

Creates a slice of array with n elements dropped from the end.

Arguments:

  1. array (Array): The array to query.
  2. n (Number): The number of elements to drop. Default is 0.

Returns:

  • (Array): Returns the slice of array.

Examples:

var array = [ 1, 2, 3, 4, 5, 6 ];

_.dropRight(array);      // [ 1, 2, 3, 4, 5, 6 ]
_.dropRight(array, 3);   // [ 1, 2, 3 ]
_.dropRight(array, 6);   // []



_.forEach(collection, iteratee)

Iterates over each element of collection, and invokes iteratee with each element. Iteratee function may exit iteration early by explicitly returning false.

Arguments:

  1. collection (Array | Object): The collection to be iterated.
  2. iteratee (Function): function (value, key|index, collection) { }, the function invoked per iteration.
    • value: The current value being processed in the collection.
    • key|index: The key or index of the current property being processed in the collection.
    • collection: The original collection.

Returns:

  • (none)

Examples:

var obj = { a: 0, b: 1, c: 'x', d: '2' },
    arr = [ 'x', 'y', 3, '0' ],
    vals1 = [],
    keys1 = [],
    vals2 = [],
    keys2 = [];

_.forEach(obj, function (val, key) {
    vals1.push(val);
    keys1.push(key);
});

console.log(vals1); // [ 0, 1, 'x', '2' ]
console.log(keys1); // [ 'a', 'b', 'c', 'd' ]

_.forEach(arr, function (val, key) {
    vals2.push(val);
    keys2.push(key);
});

console.log(vals2); // [ 'x', 'y', 3, '0' ]
console.log(keys2); // [ 0, 1, 2, 3 ]



_.map(array, iteratee)

Creates an array of values with each element returned from iteratee.

Arguments:

  1. array (Array): The array to iterate over.
  2. iterate (Function): function (value, index, array) { }, the function invoked per iteration.
    • value: The current value being processed in the array.
    • index: The index of the current value being processed in the array.
    • array: The original array.

Returns:

  • (Array): Returns the new mapped array.

Examples:

var array = [ 1, 2, 3 ];

_.map(array, String);   // [ '1', '2', '3' ]

_.map(array, function (val) {
    return val * 2;
});  // [ 2, 4, 6 ]



_.reject(collection, predicate)

Returns the elements of collection that predicate does not return truthy for.

Arguments:

  1. collection (Array|Object): The collection to iterate over.
  2. predicate (Function): function (value, key, array) { }, the function invoked per iteration.
    • value: The current value being processed in the collection.
    • key: The key or index of the current value being processed in the collection.
    • collection: The original collection.

Returns:

  • (Array): Returns the new filtered array.

Examples:

_.reject([ 1, 2, 3, 4 ], function (val) {
    return val % 2 === 0;
});  // [ 1, 3 ]



_.remove(array, predicate)

Removes all elements from array that predicate returns truthy for and returns an array of the removed elements.

Arguments:

  1. array (Array): The array to modify.
  2. predicate (Function | String | Number): function (value, index, array) { }, the function invoked per iteration.
    • value: The current value being processed in the array.
    • index: The index of the current value being processed in the array.
    • array: The original array.

Returns:

  • (Array): Returns the new array of removed elements.

Examples:

var array = [ 1, 2, 3, 4 ];

_.remove(array, function (val) {
    return val % 2 === 0;
}); // [ 2, 4 ]

console.log(array); // [ 1, 3 ]

_.remove(array, 3); // [ 3 ]
console.log(array); // [ 1 ]



_.bind(func, thisArg[, partial1[, partial2[, ... [, partialN]]]])

Creates a function that invokes func with the this binding of thisArg and partialN prepended to the arguments it receives.

Arguments:

  1. func (Function): The function to bind.
  2. thisArg (): The this binding of func.
  3. partialN (Depends): The arguments to be partially applied.

Returns:

  • (Function): Returns the new bound function.

Examples:

var greet = function (greeting, punctuation) {
    return greeting + ' ' + this.name + punctuation;
};

var person = {
    name: 'Peter',
    age: 24
};

var bound = _.bind(greet, person, 'Hello');

bound('!'); // 'Hello Peter!'



_.delay(func, wait, [, arg1[, arg2[, ...[, argN]]]])

Invokes func after wait milliseconds. Any additional arguments are provided to func when it is invoked.

Arguments:

  1. func (Function): The function to delay.
  2. wait (Number): The number of milliseconds to delay invocation.
  3. argN (Depends): The arguments to invoke func with.

Returns:

  • (Object): Returns the timer id.

Examples:

_.delay(function(text) {
    console.log(text);
}, 1000, 'Hello');

// Logs 'Hello' after one second.



_.isEmpty(value)

Check if the vlaue is an empty object. An object is empty if it has no own enumerable properties.
null is empty. Array-like values such as arguments objects, arrays, buffers, or strings are considered empty if they have a length of 0.

Arguments:

  1. value (*): The value to check.

Returns:

  • (Boolean): true if it is empty, otherwise false.

Examples:

function X () {}
X.prototype.someProp = 0;

function Y (name) {
    this.name = name;
}

_.isEmpty({});      // true
_.isEmpty(new X()); // true
_.isEmpty([]);      // true
_.isEmpty('');      // true

function foo() {
    console.log(_.isEmpty(arguments));
}

foo();                  // true
foo('a', 2, 'hello');   // false

_.isEmpty({ x: 1 });            // false
_.isEmpty(new Y('busyman'));    // false
_.isEmpty([ 2 ]);               // false
_.isEmpty('hello');             // false



_.isEqual(value, other)

Check if the tow given values are deeply equal to each other.

Arguments:

  1. value (*): The value to compare.
  2. other (*): The other value to compare.

Returns:

  • (Boolean): true if the values are deeply equal, otherwise false.

Examples:

var obj1 = {
        x: 1,
        y: [ 1, 2, 3 ],
        z: {
            m: 'hello',
            n: { p: 2, q: [ 'foo', 'bar' ] }
        }
    },
    obj2 = {
        x: 1,
        y: [ 1, 2, 3 ],
        z: {
            m: 'hello',
            n: { p: 2, q: [ 'foo', 'bar' ] }
        }
    },

_.isEqual(obj1, 'hi' );     // false
_.isEqual(obj1, {
    x: 1,
    y: [ 1, 2, 3 ]
});                         // false

_.isEqual(obj1, obj2 );     // true
console.log(obj1 === obj2); // false



_.clone(value)

Creates a shallow copy of the value.

Arguments:

  1. value (*): The value to clone.

Returns:

  • (*): The shallow cloned value.

Examples:

var objects = [ { x: 1 }, { y: 2 } ];

var shallow = _.clone(objects);

console.log(shallow[0] === objects[0]); // true



_.cloneDeep(value)

Creates a deep clone of the value.

Arguments:

  1. value (*): The value to clone.

Returns:

  • (*): The deeply cloned value.

Examples:

var objects = [ { x: 1 }, { y: 2 } ];

var deep = _.cloneDeep(objects);

console.log(deep[0] === objects[0]); // false



_.now()

This method is based on Date.now. It returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.

Arguments:

  • (none)

Returns:

  • (Number): Milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now.

Examples:

_.now();    // 1466047513349
Clone this wiki locally