Amp — 78 utility functions as individual npm modules

This page is the consolidated reference for all the amp modules in a single page for the sake of being 'cmd+f' friendly.

All modules are unit tested in a wide range of browsers (including IE6+) with a CI system composed of SauceLabs and Travis CI by using zuul and tape.

Project goals:

  • Excellent, cross-browser test coverage
  • Independently maintained and versioned
  • Strict semver for versioning
  • Try very hard to maintain APIs, ideally staying on 1.x.x version
  • Try to consider the published versions "done" code
  • Provide easy to remember names (by using namespacing)
  • Minimize unneeded interdependencies

Many of the tests and implementations were ported from Underscore.js in order to benefit from its battle-tested code. Much props to Jeremy Ashkenas and the other underscore contributors. This project would not exist if not for them and underscore's generous MIT license.

How filesizes are calculated

To give you a rough idea of what impact a given module will have on a browserify bundle's filesize we calculate it as follows:

   amp module (browserified, min + gzip)
 - empty file (browserified, min + gzip)
----------------------------------------
      estimated weight added to your app

However, this is still a flawed estimate since if you use multiple amp modules, the actual de-duped size will be even small since they likely share dependencies.

amp-add-class

amp-add-class

v1.1.0

Docs

Adds class(es) to an element.

All of the following work:

addClass(el, 'foo');
addClass(el, 'foo bar');
addClass(el, 'foo', 'bar');
addClass(el, ['foo', 'bar']);

Optimized for minimal DOM manipulation. The most common usecase of adding a single class will use native Element.classList if available. Otherwise, it will do a single read of el.className and only write back to it once, and only if something was actually changed.

note: Don't mix-and-match approaches. For example, don't do addClass(el, 'foo', ['bar', 'baz']). If you need this, flatten it first.

Example Usage

var addClass = require('amp-add-class');

var element = document.querySelector('#my-el');
element.outerHTML; //=> '<div>greetings</div>';

// basic adding
addClass(element, 'oh');
element.outerHTML; //=> '<div class="oh">greetings</div>';

// adding an existing class does nothing
addClass(element, 'oh'); 

// add multiple at once
addClass(element, 'hello', 'there'); 
element.outerHTML; //=> '<div class="oh hello there">greetings</div>';

// using array
addClass(element, ['foo', 'bar']); 
element.outerHTML; //=> '<div class="oh hello there foo bar">greetings</div>';

// add multiple at once with space-separated string
addClass(element, 'baz boo'); 
element.outerHTML; //=> '<div class="oh hello there baz boo">greetings</div>';
var hasClass = require('amp-has-class');
var isString = require('amp-is-string');
var isArray = require('amp-is-array');
var trim = require('amp-trim');
var slice = Array.prototype.slice;
var cleanup = /\s{2,}/g;
var ws = /\s+/;


module.exports = function addClass(el, cls) {
    if (arguments.length === 2 && isString(cls)) {
        cls = trim(cls).split(ws);
    } else {
        cls = isArray(cls) ? cls : slice.call(arguments, 1);    
    }
    // optimize for best, most common case
    if (cls.length === 1 && el.classList) {
        if (cls[0]) el.classList.add(cls[0]);
        return el;
    }
    var toAdd = [];
    var i = 0;
    var l = cls.length;
    var item;
    var clsName = el.className;
    // see if we have anything to add
    for (; i < l; i++) {
        item = cls[i];
        if (item && !hasClass(clsName, item)) {
            toAdd.push(item);
        }
    }
    if (toAdd.length) {
        el.className = trim((clsName + ' ' + toAdd.join(' ')).replace(cleanup, ' '));
    }
    return el;
};
var test = require('tape');
var addClass = require('./add-class');


function getEl(className) {
    var div = document.createElement('div');
    div.className = className;
    return div;
}

test('amp-add-class', function (t) {
    var el = getEl('oh');
    
    addClass(el, 'oh');
    t.equal(el.className, 'oh');   
    
    el = getEl('oh');
    addClass(el, 'oh');
    t.equal(el.className, 'oh', 'adding existing class should do nothing');   
    
    addClass(el, 'hello', 'there');
    t.equal(el.className, 'oh hello there', 'should be able to add several');   
    
    addClass(el, 'oh', 'hello', 'there');
    t.equal(el.className, 'oh hello there', 'should never add dupes');

    addClass(el, undefined, null, NaN, 0, '');
    t.equal(el.className, 'oh hello there', 'should be reasonably tolerant of nonsense');

    el = getEl('');
    addClass(el, ['oh', 'hello', 'there']);
    t.equal(el.className, 'oh hello there', 'should work with arrays too');

    el = getEl('   oh    hello  there  ');
    var clsName = el.className;
    t.equal(clsName, addClass(el, 'hello', 'there').className, 'should not touch classNames if not modifying');
    t.equal(addClass(el, 'hello', 'yo').className, 'oh hello there yo', 'should clean up className whitespacing if modifying anyway');

    el = getEl('oh');
    addClass(el, 'hello there');
    t.equal(el.className, 'oh hello there', 'supports adding space separated chars');   

    el = getEl('oh');
    addClass(el, '\t\r\nhello \n  there   ');
    t.equal(el.className, 'oh hello there', 'tolerate extra spaces when adding space separated chars');  

    t.end();
});

Estimated bundle size increase

~408 B (details)

Dependencies

amp-has-class

amp-has-class

v1.0.3

Docs

Returns true if the element has the class and false otherwise.

If the first argument is a string, it is assumed to be what you'd get from el.className. This allows it to be used repeatedly for a single element without reading from the DOM more than once.

Example Usage

var hasClass = require('amp-has-class');

var el = document.querySelector('#my-div');

el.outerHTML; //=> <div class="oh hi">hello</div>

hasClass(el, 'oh'); //=> true
hasClass(el, 'no'); //=> false

// also works with the string result of `el.className`
var className = el.className;

hasClass(className, 'oh'); //=> true
hasClass(className, 'no'); //=> false
var isString = require('amp-is-string');
var whitespaceRE = /[\t\r\n\f]/g;


// note: this is jQuery's approach
module.exports = function hasClass(el, cls) {
    var cName = (isString(el) ? el : el.className).replace(whitespaceRE, ' ');
    return (' ' + cName + ' ').indexOf(' ' + cls + ' ') !== -1;
};
var test = require('tape');
var hasClass = require('./has-class');


function getEl(className) {
    var div = document.createElement('div');
    div.className = className;
    return div;
}

test('amp-has-class', function (t) {
    t.ok(hasClass(getEl('hi'), 'hi'));
    t.ok(hasClass(getEl('hi there'), 'there'));
    t.notOk(hasClass(getEl('hi'), 'something'));
    t.notOk(hasClass(getEl('hi there'), 'something'));
    t.notOk(hasClass(getEl('hi-there'), 'hi'));
    t.notOk(hasClass(getEl('hi-there'), 'there'));
    t.notOk(hasClass(getEl('hi-there'), 'i-t'));
    t.notOk(hasClass(getEl('hi-there'), '-'));

    var className = getEl('hi there').className;
    t.ok(hasClass(className, 'hi'));
    t.ok(hasClass(className, 'there'));
    t.notOk(hasClass(className, 'something'));

    t.ok(hasClass(getEl('\thi'), 'hi'), 'can be \t issue #27');
    t.ok(hasClass(getEl('\nhi'), 'hi'), 'can be \n issue #27');
    t.ok(hasClass(getEl('\rhi'), 'hi'), 'can be \r issue #27');
    t.ok(hasClass(getEl('\fhello\fhi\f'), 'hi'), 'can be \f issue #27');

    t.end();
});

Estimated bundle size increase

~131 B (details)

Dependencies

amp-remove-class

amp-remove-class

v1.1.0

Docs

Removes class(es) from an element.

All of the following work:

removeClass(el, 'foo');
removeClass(el, 'foo bar');
removeClass(el, 'foo', 'bar');
removeClass(el, ['foo', 'bar']);

Optimized for minimal DOM manipulation. The most common usecase of removing a single class will use native Element.classList if available. Otherwise, it will do a single read of el.className and only write back to it once, and only if something was actually changed.

note: Don't mix-and-match approaches. For example, don't do removeClass(el, 'foo', ['bar', 'baz']). If you need this, flatten it first.

Example Usage

var removeClass = require('amp-remove-class');

var element = document.querySelector('#my-el');
element.outerHTML; //=> '<div class="oh hello there">greetings</div>';

removeClass(element, 'oh');
element.outerHTML; //=> '<div class="hello there">greetings</div>';

// remove multiple at once
removeClass(element, 'hello', 'there'); 
// can be done with a space-separated string
removeClass(element, 'hello there');
// can also be done by passing array
removeClass(element, ['hello', 'there']); 

element.outerHTML; //=> '<div class="">greetings</div>';
var isString = require('amp-is-string');
var isArray = require('amp-is-array');
var trim = require('amp-trim');
var slice = Array.prototype.slice;
var cleanup = /\s{2,}/g;
var ws = /\s+/;


module.exports = function removeClass(el, cls) {
    if (arguments.length === 2 && isString(cls)) {
        cls = trim(cls).split(ws);
    } else {
        cls = isArray(cls) ? cls : slice.call(arguments, 1);    
    }
    // optimize for best, most common case
    if (cls.length === 1 && el.classList) {
        if (cls[0]) el.classList.remove(cls[0]);
        return el;
    }
    // store two copies
    var clsName = ' ' + el.className + ' ';
    var result = clsName;
    var current;
    var start;
    for (var i = 0, l = cls.length; i < l; i++) {
        current = cls[i];
        start = current ? result.indexOf(' ' + current + ' ') : -1;
        if (start !== -1) {
            start += 1;
            result = result.slice(0, start) + result.slice(start + current.length);
        }
    }
    // only write if modified
    if (clsName !== result) {
        el.className = trim(result.replace(cleanup, ' '));
    }
    return el;
};
var test = require('tape');
var removeClass = require('./remove-class');


function getEl(className) {
    var div = document.createElement('div');
    div.className = className;
    return div;
}


test('amp-remove-class', function (t) {
    var el = getEl('oh hello there');
    
    removeClass(el, 'oh');
    t.equal(el.className, 'hello there');   
    
    removeClass(el, 'oh');
    t.equal(el.className, 'hello there', 'removing non-existant class should do nothing');   
    
    removeClass(el, 'hello', 'there');
    t.equal(el.className, '', 'should be able to remove several');   
    
    removeClass(el, 'oh', 'hello', 'there');
    t.equal(el.className, '', 'should be ok if doing again');

    // reset it
    el = getEl('oh hello there');

    removeClass(el, undefined, null, NaN, 0, '');
    t.equal(el.className, 'oh hello there', 'should be reasonably tolerant of nonsense');

    el = getEl('undefined null NaN');
    removeClass(el, undefined, null, NaN, 0, '');
    t.equal(el.className, 'undefined null NaN', 'should not remove classes named `undefined` etc.');

    el = getEl('oh hello there');
    t.equal(el.className, 'oh hello there');
    removeClass(el, ['oh', 'hello', 'there']);
    t.equal(el.className, '');

    el = getEl('  oh   hello there');
    var clsName = el.className;

    t.equal(clsName, removeClass(el, 'not', 'changing').className, 'should not touch classNames if not modifying');
    t.equal(removeClass(el, 'hello', 'yo').className, 'oh there', 'should clean up classNames whitespacing, if modifying anyway');

    el = removeClass(getEl('foobar'), 'foo', 'bar');
    t.equal(el.className, 'foobar');

    el = getEl('oh hello there');
    t.equal(removeClass(el, 'hello there').className, 'oh', 'should support space separated string of classes');

    el = getEl('oh hello there');
    t.equal(removeClass(el, '\r  hello \t \nthere  ').className, 'oh', 'should support other weird whitespace when using a string of classes');

    t.end();
});

Estimated bundle size increase

~357 B (details)

Dependencies

amp-toggle-class

amp-toggle-class

v1.1.0

Docs

Toggles the existence of a class on an element. If the class exists it will be removed, if it doesn't it will be added.

If a condition argument is supplied, the truthiness of that condition is what determines whether the class should exist on the element or not. This simplifies common use case of an element needing a class if condition is true. condition can be passed as either a primitive which will eventually coerce to boolean or as a function. If you pass a function, you get current element passed as a first argument.

Example Usage

var toggleClass = require('amp-toggle-class');

var element = document.querySelector('#my-el');
element.outerHTML; //=> '<div>greetings</div>';

// if no condition, toggles based on presence
toggleClass(element, 'oh');
element.outerHTML; //=> '<div class="oh">greetings</div>';

// running again, will remove it
toggleClass(element, 'oh'); 
element.outerHTML; //=> '<div class="">greetings</div>';

// toggling based on condition
// the `condition` always wins.
// Here, the class is missing, 
// but condition is falsy
// so `toggleClass` does nothing.
toggleClass(element, 'oh', false); 
element.outerHTML; //=> '<div class="">greetings</div>';
var isUndefined = require('amp-is-undefined');
var isFunction = require('amp-is-function');
var hasClass = require('amp-has-class');
var addClass = require('amp-add-class');
var removeClass = require('amp-remove-class');


var actions = {
    add: addClass,
    remove: removeClass
};

module.exports = function toggleClass(el, cls, condition) {
    var action;
    if (!isUndefined(condition)) {
        condition = isFunction(condition) ? condition.call(null, el) : condition;
        action = condition ? 'add' : 'remove';
    } else {
        action = hasClass(el, cls) ? 'remove' : 'add';
    }
    return actions[action](el, cls);
};
var test = require('tape');
var toggleClass = require('./toggle-class');


function getEl(className) {
    var div = document.createElement('div');
    div.className = className;
    return div;
}

test('amp-toggle-class', function (t) {
    var el = getEl('oh');

    toggleClass(el, 'oh');
    t.equal(el.className, '', 'removes if present without condition passed');   
    toggleClass(el, 'oh');
    t.equal(el.className, 'oh', 'puts it back when called again');   
    
    el = getEl('oh');
    toggleClass(el, 'oh', true);
    t.equal(el.className, 'oh', 'should leave it alone if condition is boolean true and class is already present');

    el = getEl('oh');
    toggleClass(el, 'hi', true);
    t.equal(el.className, 'oh hi', 'should add class if condition is boolean true');
    
    el = getEl('');
    toggleClass(el, 'oh', false);
    t.equal(el.className, '', 'should not remove class if not present and condition is false');

    el = getEl('oh');
    toggleClass(el, 'oh', false);
    t.equal(el.className, '', 'should remove class if condition is boolean false');

    // toggling with condition as a booleans
    el = getEl('oh');
    toggleClass(el, 'hi', function (element) {
        t.equal(el, element, 'should pass element to a condition function');
        return 1 + 1 === 2;
    });
    t.equal(el.className, 'oh hi', 'should add class if condition is a function returning true');

    el = getEl('oh');
    toggleClass(el, 'oh', function (element) {
        t.equal(el, element, 'should pass element to a condition function');
        return 1 + 1 === 1;
    });
    t.equal(el.className, '', 'should remove class if condition is a function returning false');

    var nonsense = [undefined, null, NaN, 0, ''];

    for (var i = 0, l = nonsense.length; i < l; i++) {
        el = getEl('ok')
        toggleClass(el, nonsense[i]);
        t.equal(el.className, 'ok', 'should be reasonably tolerant of nonsense');
    }
    
    el = getEl('   oh    hello  there  ');
    var clsName = el.className;
    t.equal(clsName, toggleClass(el, 'hello', true).className, 'should not touch classNames if not modifying');
    
    // toggling with conditions
    el = getEl('oh');
    t.equal(el, toggleClass(el, 'hi', true), 'should always return element');
    el = getEl('oh');
    t.equal(el, toggleClass(el, 'hi', false), 'should always return element');

    // toggling without conditions
    el = getEl('oh');
    t.equal(el, toggleClass(el, 'oh'), 'should always return element');
    el = getEl('oh');
    t.equal(el, toggleClass(el, 'hi'), 'should always return element');

    t.end();
});

Estimated bundle size increase

~717 B (details)

Dependencies

amp-bind

amp-bind

v1.0.1

Lodash Version: lodash.bind

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, pass arguments to the function to pre-fill them, also known as partial application.

note: If you know you're in an environment where you'll have native Function.prototype.bind (such as node.js) there's really no reason not to just use that. It even does the partial application as described above. Many JS runtimes have it these days. Notable exceptions are Phantom.js and IE8 or older.

Example Usage

var bind = require('amp-bind');

var obj = {};
var func = function (greeting, who) {
    console.log(greeting, who);    
    console.log(this === obj);
};

var bound = bind(func, obj, 'hello', 'there');

bound();
//=> 'hello there'
//=> true

//Can also act like a partial generator
var partial = bind(func, null, 'hello');

partial('again');
//=> 'hello again'
//=> false
var isFunction = require('amp-is-function');
var isObject = require('amp-is-object');
var nativeBind = Function.prototype.bind;
var slice = Array.prototype.slice;
var Ctor = function () {};


module.exports = function bind(func, context) {
    var args, bound;
    if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!isFunction(func)) throw new TypeError('Bind must be called on a function');
    args = slice.call(arguments, 2);
    bound = function() {
        if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
        Ctor.prototype = func.prototype;
        var self = new Ctor();
        Ctor.prototype = null;
        var result = func.apply(self, args.concat(slice.call(arguments)));
        if (isObject(result)) return result;
        return self;
    };
    return bound;
};
var test = require('tape');
var bind = require('./bind');


test('amp-bind', function (t) {
    var context = {name : 'moe'};
    var func = function(arg) {
        return 'name: ' + (this.name || arg);
    };
    var bound = bind(func, context);
    t.equal(bound(), 'name: moe', 'can bind a function to a context');

    bound = bind(func, context);
    t.equal(bound(), 'name: moe', 'can do OO-style binding');

    bound = bind(func, null, 'curly');
    t.equal(bound(), 'name: curly', 'can bind without specifying a context');

    func = function(salutation, name) {
        return salutation + ': ' + name;
    };
    func = bind(func, this, 'hello');
    t.equal(func('moe'), 'hello: moe', 'the function was partially applied in advance');

    func = bind(func, this, 'curly');
    t.equal(func(), 'hello: curly', 'the function was completely applied in advance');

    func = function(salutation, firstname, lastname) {
        return salutation + ': ' + firstname + ' ' + lastname;
    };
    func = bind(func, this, 'hello', 'moe', 'curly');
    t.equal(func(), 'hello: moe curly', 'the function was partially applied in advance and can accept multiple arguments');

    func = function(context, message) {
        t.ok(this == context, message);
    };
    bind(func, 0, 0, 'can bind a function to `0`')();
    bind(func, '', '', 'can bind a function to an empty string')();
    bind(func, false, false, 'can bind a function to `false`')();

    // These tests are only meaningful when using a browser without a native bind function
    // To test this with a modern browser, set underscore's nativeBind to undefined
    var F = function () { return this; };
    var boundf = bind(F, {hello: 'moe curly'});
    var Boundf = boundf; // make eslint happy.
    var newBoundf = new Boundf();
    t.equal(newBoundf.hello, undefined, 'function should not be bound to the context, to comply with ECMAScript 5');
    t.equal(boundf().hello, 'moe curly', "When called without the new operator, it's OK to be bound to the context");
    t.ok(newBoundf instanceof F, 'a bound instance is an instance of the original function');

    t.throws(function() {
        bind('notafunction');
    }, TypeError, 'throws an error when binding to a non-function');
    t.end();
});

Estimated bundle size increase

~307 B (details)

Dependencies

amp-debounce

amp-debounce

v1.0.1

Lodash Version: lodash.debounce

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. This is useful for implementing behavior that should only happen after something has stopped occuring. For example: validating an input, recalculating a layout after the window has stopped being resized, and so on.

Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead of the trailing edge of the wait interval.

Example Usage

var debounce = require('amp-debounce');

var sayHi = function () {
    console.log('hi! <3');
};
var debouncedGreeting = debounce(sayHi, 200);

// will only run *once* and only 200ms after last call
debouncedGreeting();
debouncedGreeting();
debouncedGreeting();
debouncedGreeting();
// *200ms pass*
//=> 'hi'
var now = Date.now;

// IE < 9
if (!now) {
    now = function () {
        return (new Date()).valueOf();
    };
}

module.exports = function debounce(func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function () {
        var last = now() - timestamp;

        if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last);
        } else {
            timeout = null;
            if (!immediate) {
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            }
        }
    };

    return function () {
        context = this;
        args = arguments;
        timestamp = now();
        var callNow = immediate && !timeout;
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
            result = func.apply(context, args);
            context = args = null;
        }

        return result;
    };
};
var test = require('tape');
var debounce = require('./debounce');
var delay = require('amp-delay');


test('amp-debounce', function (t) {
    t.plan(1);
    var counter = 0;
    var incr = function () {
        counter++;
    };
    var debouncedIncr = debounce(incr, 64);
    debouncedIncr();
    debouncedIncr();
    delay(debouncedIncr, 32);
    delay(function () {
        t.equal(counter, 1, 'incr was debounced');
        t.end();
    }, 500);
});

test('debounce asap', function (t) {
    t.plan(4);
    var a, b;
    var counter = 0;
    var incr = function () {
        return ++counter;
    };
    var debouncedIncr = debounce(incr, 100, true);
    a = debouncedIncr();
    b = debouncedIncr();
    t.equal(a, 1);
    t.equal(b, 1);
    t.equal(counter, 1, 'incr was called immediately');
    delay(debouncedIncr, 16);
    delay(debouncedIncr, 32);
    delay(debouncedIncr, 48);
    delay(function(){
        t.equal(counter, 1, 'incr was debounced');
        t.end();
    }, 500);
});

test('debounce asap recursively', function (t) {
    t.plan(2);
    var counter = 0;
    var debouncedIncr = debounce(function(){
        counter++;
        if (counter < 10) debouncedIncr();
    }, 32, true);
    debouncedIncr();
    t.equal(counter, 1, 'incr was called immediately');
    delay(function(){
        t.equal(counter, 1, 'incr was debounced');
        t.end();
    }, 500);
});

test('debounce after system time is set backwards', function (t) {
    t.plan(2);
    var counter = 0;
    var origNowFunc = Date.now;
    var debouncedIncr = debounce(function () {
        counter++;
    }, 50, true);

    debouncedIncr();
    t.equal(counter, 1, 'incr was called immediately');

    var newNow = function () {
        return new Date(2013, 0, 1, 1, 1, 1);
    };

    delay(function() {
        debouncedIncr();
        t.equal(counter, 2, 'incr was debounced successfully');
        t.end();
        newNow = origNowFunc;
    }, 200);
});

test('debounce re-entrant', function (t) {
    t.plan(2);
    var sequence = [
        ['b1', 'b2']
    ];
    var value = '';
    var debouncedAppend;
    var append = function(arg){
        value += this + arg;
        var args = sequence.pop();
        if (args) {
            debouncedAppend.call(args[0], args[1]);
        }
    };
    debouncedAppend = debounce(append, 32);
    debouncedAppend.call('a1', 'a2');
    t.equal(value, '');
    delay(function(){
        t.equal(value, 'a1a2b1b2', 'append was debounced successfully');
        t.end();
    }, 500);
});

Estimated bundle size increase

~148 B (details)

Dependencies

(none)

none

amp-delay

amp-delay

v1.0.1

Lodash Version: lodash.delay

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Slightly cleaner version of setTimeout, it invokes function after specified milliseconds. But also lets you set a context in which to call it (note that this differs from underscore's implementation).

Returns the result of setTimeout so you can still use that with clearTimeout if you need to halt it for some reason.

Related: for an excellent visual explanation of event loop and how things like setTimeout actually work, watch Philip Robert's talk "What the heck is the event loop anyway?".

Example Usage

var delay = require('amp-delay');

var sayHi = function (name) {
    console.log('Oh, hello there!');
};

delay(sayHi, 200);
//=> 200ms pause
//=> 'Oh, hello there!'

// with context
var obj = {
    name: 'Mr. Fox',
    someMethod: function () {
        // here we maintain context
        delay(this.otherMethod, 200, this);
    },
    otherMethod: function () {
        // now we can still access `this`
        console.log('Oh, hello there, ' + this.name + '!');
    }
};

obj.someMethod();
//=> 200ms pause
//=> 'Oh, hello there, Mr. Fox!'
var bind = require('amp-bind');


module.exports = function delay(func, wait, context) {
    if (context) func = bind(func, context);
    return setTimeout(func, wait);
};
var test = require('tape');
var delay = require('./delay');


test('amp-delay', function (t) {
    t.plan(3);

    var obj = {
        init: function () {
            // here we maintain context
            delay(this.sayHi, 0, this);
        },
        sayHi: function () {
            t.equal(this, obj, 'maintains context');
        }
    };
    obj.init();

    var delayed = false;

    delay(function(){
        delayed = true;
    }, 100);
    setTimeout(function () {
        t.ok(!delayed, "didn't delay the function quite yet");
    }, 50);
    setTimeout(function () {
        t.ok(delayed, 'delayed the function');
        t.end();
    }, 150);
});

Estimated bundle size increase

~345 B (details)

Dependencies

amp-limit-calls

amp-limit-calls

v1.0.2

Lodash Version: lodash.before

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Creates a version of the function that will be run a maximum of limit times. The result of the last function call is cached and returned for any subsequent calls.

Example Usage

var limitCalls = require('amp-limit-calls');

var timesCalled = 0;
var getCount = function () {
    return ++timesCalled;
}
var modified = limitCalls(getCount, 2); //=> returns modified function

console.log(modified()); //=> 1
console.log(modified()); //=> 2
console.log(modified()); //=> 2
module.exports = function limitCalls(fn, times) {
    var memo;
    return function() {
        if (times-- > 0) {
            memo = fn.apply(this, arguments);
        } else {
            fn = null;
        }
        return memo;
    };
};
var test = require('tape');
var limitCalls = require('./limit-calls');


test('amp-limit-calls', function (t) {
    var testBefore = function(limit, timesToCall) {
        var called = 0;
        var modified = limitCalls(function () {
            called++;
        }, limit);
        while (timesToCall--) modified();
        return called;
    };

    t.equal(testBefore(5, 5), 5, 'limitCalls(N) should not fire after being called N times');
    t.equal(testBefore(5, 4), 4, 'limitCalls(N) should fire limitCalls being called N times');
    t.equal(testBefore(0, 0), 0, 'limitCalls(0) should not fire immediately');
    t.equal(testBefore(0, 1), 0, 'limitCalls(0) should not fire when first invoked');

    var context = {num: 0};
    var increment = limitCalls(function () {
        return ++this.num;
    }, 3);

    // run it a bunch
    increment.call(context);
    increment.call(context);
    increment.call(context);
    increment.call(context);
    increment.call(context);

    t.equal(increment(), 3, 'stores a memo to the last value');
    t.equal(context.num, 3, 'provides context');
    t.end();
});

Estimated bundle size increase

~45 B (details)

Dependencies

(none)

none

amp-negate

amp-negate

v1.0.0

Lodash Version: lodash.negate

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns a new negated version of the predicate function.

Example Usage

var negate = require('amp-negate');


negate(function() { return true; }); //=> false
negate(function() { return false; }); //=> true
module.exports = function negate(predicate) {
    return function() {
        return !predicate.apply(this, arguments);
    };
};
var test = require('tape');
var negate = require('./negate');


test('amp-negate', function (t) {
    var isOdd = function(n){ return n & 1; };
    t.equal(negate(isOdd)(2), true, 'should return the complement of the given function');
    t.equal(negate(isOdd)(3), false, 'should return the complement of the given function');
    t.end();
});

Estimated bundle size increase

~29 B (details)

Dependencies

(none)

none

amp-once

amp-once

v1.0.1

Lodash Version: lodash.once

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

Example Usage

var once = require('amp-once');

var counter = 0;
var modified = once(function () {
    console.log('called!');
    return ++counter;
});

modified(); 
// logs out "called!"
//=> 1
// subsequent calls returns result from
// first without actually running again.
modified(); //=> 1
modified(); //=> 1
var limitCalls = require('amp-limit-calls');


module.exports = function once(fn) {
    return limitCalls(fn, 1);
};
var test = require('tape');
var once = require('./once');


test('amp-once', function (t) {
    var num = 0;
    var increment = once(function () {
        return ++num;
    });
    increment();
    increment();
    t.equal(num, 1, 'should never call more than once');
    t.equal(increment(), 1, 'stores a memo of the last value');
    var sayHi = once(function (name) {
        return name;
    });
    t.equal(sayHi('there'), 'there', 'make sure arguments are being applied');
    t.equal(sayHi('new thing'), 'there', 'should still return the same thing');
    t.end();
});

Estimated bundle size increase

~82 B (details)

Dependencies

amp-times

amp-times

v1.0.0

Lodash Version: lodash.times

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Runs a function n times and returns an Array containing all the accumulated results. Your iteratee function will be called with an index so it knows which iteration is currently running.

Example Usage

var times = require('amp-times');

var timesCalled = 0;
var logCalls = function () {
    console.log(timesCalled);
    return ++timesCalled;
};

times(2, logCalls);
//=> 0
//=> 1
var createCallback = require('amp-create-callback');


module.exports = function times(n, iteratee, context) {
    var accum = Array(Math.max(0, n));
    iteratee = createCallback(iteratee, context, 1);
    for (var i = 0; i < n; i++) accum[i] = iteratee(i);
    return accum;
};
var test = require('tape');
var times = require('./times');
var identity = function (x) { return x; };


test('amp-times', function (t) {
    // is 0 indexed
    var vals = [];
    times(3, function (i) { vals.push(i); });
    t.deepEqual(vals, [0, 1, 2], 'is 0 indexed');

    // collects return values
    t.deepEqual([0, 1, 2], times(3, function(i) { return i; }), 'collects return values');

    // optionally applies context to iterated function
    var context = {count: 0};
    times(3, function(){
        this.count++;
    }, context);
    t.equal(context.count, 3, 'optionally applies context to the iterated function');

    // doesn't barf on weird values
    t.deepEqual(times(0, identity), [], 'doesn\'t barf on 0');
    t.deepEqual(times(-1, identity), [], 'doesn\'t barf on -1');
    t.deepEqual(times(parseFloat('-Infinity'), identity), [], 'doesn\'t barf on -Infinity');

    t.end();
});

Estimated bundle size increase

~178 B (details)

Dependencies

amp-contains

amp-contains

v1.0.1

Lodash Version: lodash.contains

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Determines whether the array or object contains an item. Returns true or false. Note that in the case of an object it checks the values not key names.

Example Usage

var contains = require('amp-contains');

console.log(contains(['hi'], 'hi')); //=> true

// with objects, keys don't matter it just looks value that matches
console.log(contains({hi: 'there'}, 'there')); //=> true
console.log(contains({hi: 'there'}, 'hi')); //=> false
var values = require('amp-values');
var indexOf = require('amp-index-of');


module.exports = function contains(obj, target) {
    if (obj == null) return false;
    if (obj.length !== +obj.length) obj = values(obj);
    return indexOf(obj, target) >= 0;
};
var test = require('tape');
var contains = require('./contains');


test('amp-contains', function (t) {
    t.ok(contains(['hi', 'there'], 'hi'));
    t.ok(contains(['hi', 1], 1));
    var obj = {};
    t.ok([obj, 'hi'], obj);
    t.ok(!contains(undefined, 'hi'));
    t.end();
});

Estimated bundle size increase

~484 B (details)

Dependencies

amp-each

amp-each

v1.0.1

Lodash Version: lodash.foreach

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

You can think of this as an Array.prototype.forEach that also works on objects and rather than returning undefined as the native forEach does, it returns the list/object you're iterating over.

It iterates over all items in an array or keys in an object one at a time, passing each item to the function you supply. That function's this will be the context object, you provide if you passed one as a third argument.

Your function will be called with three arguments. In the case of an Array or arguments object those items will be (item, index, list).

In the case of an object the arguments will be (value, key, list).

Example Usage

var each = require('amp-each');

var list = ['oh', 'hello', 'there'];
var obj = {name: 'Henrik', greeting: 'Oh, hello there!'};

each(list, function (item, index) {
    console.log(item, index);
});
//=> 'oh', 0
//=> 'hi', 1
//=> 'there', 2

each(obj, function (value, key) {
    console.log(value, key);
});
//=> 'Henrik', 'name'
//=> 'Oh, hello there!', 'greeting'

// with a context
var myContext = {thing: 'stuff'};

each([1, 2], function () {
    console.log(this);
}, myContext);
//=> {thing: 'stuff'}
//=> {thing: 'stuff'}
var objKeys = require('amp-keys');
var createCallback = require('amp-create-callback');


module.exports = function each(obj, iteratee, context) {
    if (obj == null) return obj;
    iteratee = createCallback(iteratee, context);
    var i, length = obj.length;
    if (length === +length) {
        for (i = 0; i < length; i++) {
            iteratee(obj[i], i, obj);
        }
    } else {
        var keys = objKeys(obj);
        for (i = 0, length = keys.length; i < length; i++) {
            iteratee(obj[keys[i]], keys[i], obj);
        }
    }
    return obj;
};
var test = require('tape');
var each = require('./each');
var contains = require('amp-contains');


test('amp-each', function (t) {
    each([1, 2, 3], function(num, i) {
        t.equal(num, i + 1, 'each iterators provide value and iteration count');
    });

    var answers = [];
    each([1, 2, 3], function(num) {
        answers.push(num * this.multiplier);
    }, {multiplier : 5});
    t.deepEqual(answers, [5, 10, 15], 'context object property accessed');

    answers = [];
    each([1, 2, 3], function(num){ answers.push(num); });
    t.deepEqual(answers, [1, 2, 3], 'aliased as "forEach"');

    answers = [];
    var obj = {one : 1, two : 2, three : 3};
    obj.constructor.prototype.four = 4;
    each(obj, function(value, key){ answers.push(key); });
    t.deepEqual(answers, ['one', 'two', 'three'], 'iterating over objects works, and ignores the object prototype.');
    delete obj.constructor.prototype.four;

    var answer = null;
    each([1, 2, 3], function(num, index, arr){ if (contains(arr, num)) answer = true; });
    t.ok(answer, 'can reference the original collection from inside the iterator');

    answers = 0;
    each(null, function(){ ++answers; });
    t.equal(answers, 0, 'handles a null properly');

    each(false, function(){});

    var a = [1, 2, 3];
    t.strictEqual(each(a, function(){}), a);
    t.strictEqual(each(null, function(){}), null);

    var b = [1, 2, 3];
    b.length = 100;
    answers = 0;
    each(b, function(){ ++answers; });
    t.equal(answers, 100, 'enumerates [0, length)');


    var collection = [1, 2, 3], count = 0;
    each(collection, function() {
      if (count < 10) collection.push(count++);
    });
    t.equal(count, 3);

    collection = {a: 1, b: 2, c: 3};
    count = 0;
    each(collection, function() {
      if (count < 10) collection[count] = count++;
    });
    t.equal(count, 3);
    t.end();
});

Estimated bundle size increase

~583 B (details)

Dependencies

amp-every

amp-every

v1.0.1

Lodash Version: lodash.every

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if all of the values in the collection pass the function test you provide and false otherwise. Stops looping once a single failure is found.

Example Usage

var every = require('amp-every');

var isEven = function(num){
    return num % 2 === 0;
};

every([0, 10, 28], isEven); //=> true
every([0, 11, 28], isEven); //=> false
var objKeys = require('amp-keys');
var iteratee = require('amp-iteratee');


module.exports = function every(obj, func, context) {
    if (obj == null) return true;
    var keys = obj.length !== +obj.length && objKeys(obj);
    var length = (keys || obj).length;
    var index, currentKey;
    
    func = iteratee(func, context);
    
    for (index = 0; index < length; index++) {
        currentKey = keys ? keys[index] : index;
        if (!func(obj[currentKey], currentKey, obj)) return false;
    }
    return true;
};
var test = require('tape');
var every = require('./every');
var isNumber = require('amp-is-number');
var isObject = require('amp-is-object');


test('amp-every', function (t) {
    var identity = function (val) {
        return val;
    };

    t.ok(every([], identity), 'the empty set');
    t.ok(every([true, true, true], identity), 'every true values');
    t.notOk(every([true, false, true], identity), 'one false value');
    
    var isEven = function(num){
        return num % 2 === 0;
    };

    t.ok(every([0, 10, 28], isEven), 'even numbers');
    t.notOk(every([0, 11, 28], isEven), 'an odd number');

    t.ok(every([1], identity) === true, 'cast to boolean - true');
    t.ok(every([0], identity) === false, 'cast to boolean - false');
    t.notOk(every([undefined, undefined, undefined], identity), 'works with arrays of undefined');

    var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
    t.notOk(every(list, {a: 1, b: 2}), 'Can be called with object');
    t.ok(every(list, 'a'), 'String mapped to object property');

    list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}];
    t.ok(every(list, {b: 2}), 'Can be called with object');
    t.notOk(every(list, 'c'), 'String mapped to object property');

    t.ok(every({a: 1, b: 2, c: 3, d: 4}, isNumber), 'takes objects');
    t.notOk(every({a: 1, b: 2, c: 3, d: 4}, isObject), 'takes objects');
    
    var hasProperty = function (value) {
        return !!this[value];
    };

    t.ok(every(['a', 'b', 'c', 'd'], hasProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works');
    t.notOk(every(['a', 'b', 'c', 'd', 'f'], hasProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works');
    t.end();
});

Estimated bundle size increase

~867 B (details)

Dependencies

amp-filter

amp-filter

v1.0.1

Lodash Version: lodash.filter

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Looks through each value in the collection, returning an array of all the values that pass the truth test function you pass in. Alternatively you can pass in an attributeObject to use for truth testing.

Example Usage

var filter = require('amp-filter');

var isEven = function(num){
    return num % 2 === 0;
};

filter([1, 2, 3, 4], isEven); //=> [2, 4]
filter({one: 1, two: 2, three: 3, four: 4}, isEven); //=> [2, 4]

filter([{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}], {a: 1}); //[{a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]
var iteratee = require('amp-iteratee');
var each = require('amp-each');


module.exports = function filter(obj, func, context) {
    var results = [];
    if (obj == null) return results;
    func = iteratee(func, context);
    each(obj, function(value, index, list) {
        if (func(value, index, list)) results.push(value);
    });
    return results;
};
var test = require('tape');
var filter = require('./filter');


test('amp-filter', function (t) {
    var evenArray = [1, 2, 3, 4, 5, 6];
    var evenObject = {one: 1, two: 2, three: 3};
    
    var isEven = function(num){ 
        return num % 2 === 0;
    };

    t.deepEqual(filter(evenArray, isEven), [2, 4, 6]);
    t.deepEqual(filter(evenObject, isEven), [2], 'can filter objects');
    t.deepEqual(filter([{}, evenObject, []], 'two'), [evenObject], 'predicate string map to object properties');

    filter([1], function() {
        t.equal(this, evenObject, 'given context');
    }, evenObject);

    // Can be used like amp-where.
    var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
    
    t.deepEqual(filter(list, {a: 1}), [{a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]);
    t.deepEqual(filter(list, {b: 2}), [{a: 1, b: 2}, {a: 2, b: 2}]);
    t.deepEqual(filter(list, {}), list, 'Empty object accepts all items');
    
    t.end();
});

Estimated bundle size increase

~921 B (details)

Dependencies

amp-find

amp-find

v1.0.0

Lodash Version: lodash.find

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns the first value in a collection that passes the truth test function you pass in, stopping once found. If none is found, it returns undefined. Alternatively you can pass in an attributeObject instead of a function to use for truth testing. This obviates the need for a findWhere module.

Example Usage

var find = require('amp-find');

var isEven = function(num){
    return num % 2 === 0;
};

find([1, 2, 3, 4], isEven); //=> 2

find([{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}], {a: 1}); //{a: 1, b: 2}
var iteratee = require('amp-iteratee');
var some = require('amp-some');


module.exports = function find(obj, func, context) {
    var result;
    if (obj == null) return result;
    func = iteratee(func, context);
    some(obj, function (value, index, list) {
        if (func(value, index, list)) {
            result = value;
            return true;
        }
    });
    return result;
};
var test = require('tape');
var find = require('./find');


test('amp-find', function (t) {
    var evenArray = [1, 2, 3, 4, 5, 6];
    var evenObject = {one: 1, two: 2, three: 3, four: 4};

    var isEven = function(num){
        return num % 2 === 0;
    };

    t.equal(find(evenArray, isEven), 2, 'finds first even value');
    t.equal(find(evenObject, isEven), 2, 'can filter objects');

    t.equal(find(evenObject, function () { return false; }), undefined, 'returns undefined if value not found');

    find([1], function () {
        t.equal(this, evenObject, 'given context');
    }, evenObject);

    // Can be used a where function.
    var list = [ {a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4} ];

    t.deepEqual(find(list, {a: 1}), {a: 1, b: 2});

    t.end();
});

Estimated bundle size increase

~919 B (details)

Dependencies

amp-invoke

amp-invoke

v1.0.0

Lodash Version: lodash.invoke

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Calls the given methodName on each item in the list. Extra arguments will be used to call that method. Returns an array of results.

If methodName is a function it will be applied to each item in the list as if it were a method on the object.

Example Usage

var invoke = require('amp-invoke');

var hello = function (name) {
    console.log('oh, hello ' + name);
};

var people = [
    { sayHi: hello },
    { sayHi: hello },
    { huh: 'i dont have that method' }
];

invoke(people, 'sayHi', 'there');
//=> oh, hello there
//=> oh, hello there
var isFunction = require('amp-is-function');
var map = require('amp-map');
var slice = Array.prototype.slice;


module.exports = function invoke(obj, method) {
    var args = slice.call(arguments, 2);
    var isFunc = isFunction(method);
    return map(obj, function(value) {
        var func = isFunc ? method : value[method];
        return func == null ? func : func.apply(value, args);
    });
};
var test = require('tape');
var invoke = require('./invoke');


test('amp-invoke', function (t) {
    var list = [[5, 1, 7], [3, 2, 1]];
    var result = invoke(list, 'sort');
    t.deepEqual(result[0], [1, 5, 7], 'first array sorted');
    t.deepEqual(result[1], [1, 2, 3], 'second array sorted');

    invoke([{
        method: function() {
            t.deepEqual([].slice.call(arguments), [1, 2, 3], 'called with arguments');
        }
    }], 'method', 1, 2, 3);

    var people = [
        {greeting: 'hi'},
        {greeting: 'there'}
    ];

    t.deepEqual(invoke(people, function () {
        return this.greeting;
    }), ['hi', 'there'], 'works when passed a function');

    t.equal(invoke([{a: null}], 'a')[0], null);
    t.equal(invoke([{}], 'a')[0], void 0);
    t.equal(invoke([{a: function () { return 1; }}], 'a')[0], 1);

    var res = invoke([{a: null}, {}, {a: function () { return 1; }}], 'a')

    t.equal(res[0], null, 'handles null');
    t.equal(res[1], void 0, 'handles missing');
    t.equal(res[2], 1, 'handles method');
    t.equal(res.length, 3, 'has right results');

    t.end();
});

Estimated bundle size increase

~939 B (details)

Dependencies

amp-map

amp-map

v1.0.1

Lodash Version: lodash.map

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns an new array of values by mapping each value in list through the function you provide (the iteratee). If passed an object instead of an array your function will be called with the arguments (value, key, object).

This works like Array.prototype.map but works for objects and works in IE < 9.

Example Usage

var map = require('amp-map');

var array = ['oh', 'hello', 'there'];

var result = map(array, function (item, index) {
    console.log(item, index);
    return item.length;
});
//=> 'oh', 0
//=> 'hello', 1
//=> 'there', 2
console.log(result); //=> [2, 5, 5]

// also works on objects
var obj = {
    name: 'swede',
    greeting: 'hej'
};

result = map(obj, function (value, key) {
    console.log(value, key);
    return value.length;
});
//=> 'swede', 'name'
//=> 'hej', 'greeting'
console.log(result); //=> [5, 3]
var createIteratee = require('amp-iteratee');
var objKeys = require('amp-keys');


module.exports = function map(obj, iteratee, context) {
    if (obj == null) return [];
    iteratee = createIteratee(iteratee, context, 3);
    var keys = obj.length !== +obj.length && objKeys(obj);
    var length = (keys || obj).length;
    var results = Array(length);
    var currentKey;
    var index = 0;
    for (; index < length; index++) {
        currentKey = keys ? keys[index] : index;
        results[index] = iteratee(obj[currentKey], currentKey, obj);
    }
    return results;
};
var test = require('tape');
var map = require('./map');


test('amp-map', function (t) {
    var doubled = map([1, 2, 3], function(num){ return num * 2; });
    t.deepEqual(doubled, [2, 4, 6], 'doubled numbers');

    var tripled = map([1, 2, 3], function(num){ return num * this.multiplier; }, {multiplier : 3});
    t.deepEqual(tripled, [3, 6, 9], 'tripled numbers with context');

    var ids = map({length: 2, 0: {id: '1'}, 1: {id: '2'}}, function(n){
        return n.id;
    });
    t.deepEqual(ids, ['1', '2'], 'Can use collection methods on Array-likes.');

    t.deepEqual(map(null, function () {}), [], 'handles a null properly');

    t.deepEqual(map([1], function() {
        return this.length;
    }, [5]), [1], 'called with context');

    // Passing a property name like _.pluck.
    var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}];
    t.deepEqual(map(people, 'name'), ['moe', 'curly'], 'predicate string map to object properties');
    t.end();
});

Estimated bundle size increase

~868 B (details)

Dependencies

amp-pluck

amp-pluck

v1.0.0

Lodash Version: lodash.pluck

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Extracts the named value of a property from every item in a collection and returns them in an array.

Example Usage

var pluck = require('amp-pluck');

var items = [{name: 'Cog', price: 100}, {name: 'Sprocket', price: 99}];

pluck(items, 'name'); //=> ['Cog', 'Sprocket']
var property = require('amp-property');
var map = require('amp-map');


module.exports = function(obj, key) {
    return map(obj, property(key));
};
var test = require('tape');
var pluck = require('./pluck');


test('amp-pluck', function (t) {
    var items = [{name: 'Cog', price: 100}, {name: 'Sprocket', price: 99}];

    t.deepEqual(pluck(items, 'name'), ['Cog', 'Sprocket'], 'pulls names out of objects');
    
    // this is written this way because IE does weird things
    // with array literals that are declared with undefineds
    // [undefined, undefined]
    var expected = [];
    expected.push(undefined, undefined);
    t.deepEqual(pluck(items, 'height'), expected, 'pulls height out of objects');
    
    t.end();
});

Estimated bundle size increase

~898 B (details)

Dependencies

amp-reduce

amp-reduce

v1.0.0

Lodash Version: lodash.reduce

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Boils down a list of values or an object into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iteratee. Iteratee will be called with four arguments (memo, value, index || key, list || object).

If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list. Instead, the first element is passed as the memo in the invocation of the iteratee on the next element in the list.

Example Usage

var reduce = require('amp-reduce');

var list = [1, 2, 3, 4];
var obj = {one: 1, two: 2, three: 3, four: 4};

var sumList = reduce(list, function(memo, value) {
	return memo + value;
});
// => 10

var sumObject = reduce(obj, function(memo, value, key) {
	return memo + obj[key];
});
// => 10
var createCallback = require('amp-create-callback');
var objKeys = require('amp-keys');


module.exports = function reduce(obj, iteratee, memo, context) {
    if (obj == null) obj = [];
    iteratee = createCallback(iteratee, context, 4);
    var keys = obj.length !== +obj.length && objKeys(obj);
    var length = (keys || obj).length;
    var index = 0;
    var currentKey;
    if (arguments.length < 3) {
        if (!length) {
            throw new TypeError('Reduce of empty array with no initial value');
        }
        memo = obj[keys ? keys[index++] : index++];
    }
    for (; index < length; index++) {
        currentKey = keys ? keys[index] : index;
        memo = iteratee(memo, obj[currentKey], currentKey, obj);
    }
    return memo;
};
var test = require('tape');
var reduce = require('./reduce');


test('amp-reduce', function (t) {
    var sum = reduce([1, 2, 3], function(sum, num){ return sum + num; }, 0);
    t.equal(sum, 6, 'can sum up an array');

    sum = reduce({one: 1, two: 2, three: 3}, function(sum, num, key, obj){ return sum + obj[key]; }, 0);
    t.equal(sum, 6, 'can sum up an object');

    var context = {multiplier : 3};
    sum = reduce([1, 2, 3], function(sum, num){ return sum + num * this.multiplier; }, 0, context);
    t.equal(sum, 18, 'can reduce with a context object');

    sum = reduce([1, 2, 3], function(sum, num){ return sum + num; });
    t.equal(sum, 6, 'default initial value');

    var prod = reduce([1, 2, 3, 4], function(prod, num){ return prod * num; });
    t.equal(prod, 24, 'can reduce via multiplication');

    t.ok(reduce(null, function() {}, 138) === 138, 'handles a null (with initial value) properly');
    t.equal(reduce([], function() {}, undefined), undefined, 'undefined can be passed as a special case');
    t.equal(reduce(['_'], function() {}), '_', 'collection of length one with no initial value returns the first item');
    t.throws(function() {
        reduce([], function() {});
    }, TypeError, 'throws TypeError when array is empty and no initial value');

    t.throws(function() {
        reduce({}, function() {});
    }, TypeError, 'throws TypeError when object is empty and no initial value');

    t.end();
});

Estimated bundle size increase

~651 B (details)

Dependencies

amp-reject

amp-reject

v1.0.0

Lodash Version: lodash.reject

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns the values in a collection without the elements that the truth test passes. The opposite of amp-filter. Alternatively you can pass in an attributeObject to use for truth testing.

Example Usage

var reject = require('amp-reject');

reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); //[1, 3, 5]

reject([{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}], {a: 1}); //[{a: 2, b: 2}]

var negate = require('amp-negate');
var filter = require('amp-filter');
var iteratee = require('amp-iteratee');


module.exports = function reject(obj, predicate, context) {
    return filter(obj, negate(iteratee(predicate)), context);
};
var test = require('tape');
var reject = require('./reject');


test('amp-reject', function (t) {
    var odds = reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 === 0; });
    t.deepEqual(odds, [1, 3, 5], 'rejected each even number');

    var context = 'obj';

    var evens = reject([1, 2, 3, 4, 5, 6], function(num){
      t.equal(context, 'obj');
      return num % 2 !== 0;
    }, context);
    t.deepEqual(evens, [2, 4, 6], 'rejected each odd number');

    t.deepEqual(reject([odds, {one: 1, two: 2, three: 3}], 'two'), [odds], 'predicate string map to object properties');

    // Can be used like reject-where.
    var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
    t.deepEqual(reject(list, {a: 1}), [{a: 2, b: 2}]);
    t.deepEqual(reject(list, {b: 2}), [{a: 1, b: 3}, {a: 1, b: 4}]);
    t.deepEqual(reject(list, {}), [], 'Returns empty list given empty object');
    t.deepEqual(reject(list, []), [], 'Returns empty list given empty array');
    t.end();
});

Estimated bundle size increase

~986 B (details)

Dependencies

amp-sample

amp-sample

v1.0.0

Lodash Version: lodash.sample

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns n random values from a collection. If n is not specified, returns a single random element.

Example Usage

var sample = require('amp-sample');

sample([1, 2, 3, 4, 5, 6]); //4, sometimes
sample([1, 2, 3, 4, 5, 6], 3); //[1, 6, 2], sometimes
var values = require('amp-values');
var random = require('amp-random');
var shuffle = require('amp-shuffle');


module.exports = function sample(obj, n, guard) {
    if (n == null || guard) {
        if (obj.length !== +obj.length) obj = values(obj);
        return obj[random(obj.length - 1)];
    }
    return shuffle(obj).slice(0, Math.max(0, n));
};
var test = require('tape');
var sample = require('./sample');
var contains = require('amp-contains');
var range = require('amp-range');


test('amp-sample', function (t) {
    var numbers = range(10);
    var allSampled = sample(numbers, 10).sort();
    t.deepEqual(allSampled, numbers, 'contains the same members before and after sample');
    allSampled = sample(numbers, 20).sort();
    t.deepEqual(allSampled, numbers, 'also works when sampling more objects than are present');
    t.ok(contains(numbers, sample(numbers)), 'sampling a single element returns something from the array');
    t.strictEqual(sample([]), undefined, 'sampling empty array with no number returns undefined');
    t.notStrictEqual(sample([], 5), [], 'sampling empty array with a number returns an empty array');
    t.notStrictEqual(sample([1, 2, 3], 0), [], 'sampling an array with 0 picks returns an empty array');
    t.deepEqual(sample([1, 2], -1), [], 'sampling a negative number of picks returns an empty array');
    t.ok(contains([1, 2, 3], sample({a: 1, b: 2, c: 3})), 'sample one value from an object');
    t.end();
});

Estimated bundle size increase

~626 B (details)

Dependencies

amp-shuffle

amp-shuffle

v1.0.0

Lodash Version: lodash.shuffle

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle.

Example Usage

var shuffle = require('amp-shuffle');

shuffle([1, 2, 3, 4, 5, 6]);// [2, 5, 1, 6, 1, 4], sometimes
var values = require('amp-values');
var random = require('amp-random');


module.exports = function shuffle(obj) {
    var set = obj && obj.length === +obj.length ? obj : values(obj);
    var length = set.length;
    var shuffled = Array(length);
    for (var index = 0, rand; index < length; index++) {
        rand = random(0, index);
        if (rand !== index) shuffled[index] = shuffled[rand];
        shuffled[rand] = set[index];
    }
    return shuffled;
};
var test = require('tape');
var shuffle = require('./shuffle');
var range = require('amp-range');
var every = require('amp-every');
var contains = require('amp-contains');
var bind = require('amp-bind');


test('amp-shuffle', function (t) {
    var numbers = range(10);
    var shuffled = shuffle(numbers);
    t.notStrictEqual(numbers, shuffled, 'original object is unmodified');
    t.ok(every(range(10), function() { //appears consistent?
        return every(numbers, bind(contains, null, numbers));
    }), 'contains the same members before and after shuffle');

    shuffled = shuffle({a: 1, b: 2, c: 3, d: 4});
    t.equal(shuffled.length, 4);
    t.deepEqual(shuffled.sort(), [1, 2, 3, 4], 'works on objects');
    t.end();
});

Estimated bundle size increase

~560 B (details)

Dependencies

amp-size

amp-size

v1.0.1

Lodash Version: lodash.size

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Return the number of values in the list or keys (if you pass it an object).

Example Usage

var size = require('amp-size');

size([1, 2, 3]); //=> 3
size({hi: 'there', oh: 'hello there'}); //=> 2
var keys = require('amp-keys');


module.exports = function size(obj) {
    if (obj == null) return 0;
    return obj.length === +obj.length ? obj.length : keys(obj).length;
};
var test = require('tape');
var size = require('./size');


test('amp-size', function (t) {
    t.equal(size({one : 1, two : 2, three : 3}), 3, 'can compute the size of an object');
    t.equal(size([1, 2, 3]), 3, 'can compute the size of an array');
    t.equal(size({length: 3, 0: 0, 1: 0, 2: 0}), 3, 'can compute the size of Array-likes');

    var func = function() {
        return size(arguments);
    };

    t.equal(func(1, 2, 3, 4), 4, 'can test the size of the arguments object');

    t.equal(size('hello'), 5, 'can compute the size of a string literal');
    t.equal(size(new String('hello')), 5, 'can compute the size of string object');

    t.equal(size(null), 0, 'handles nulls');
    t.end();
});

Estimated bundle size increase

~420 B (details)

Dependencies

amp-some

amp-some

v1.0.1

Lodash Version: lodash.some

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if any of the values in the list pass the passed in test function. Stops iterating once found.

If no test function is passed, looks for any "truthy" value.

Example Usage

var some = require('amp-some');

some([false, true]); //=> true

var isEven = function (num) {
    return num % 2 === 0;
};

some([1, 3, 6, 14], isEven); //=> true 
// the `14` would never be checked
// because `6` passes

var iteratee = require('amp-iteratee');
var objKeys = require('amp-keys');


module.exports = function some(obj, func, context) {
    if (obj == null) return false;
    var keys = obj.length !== +obj.length && objKeys(obj);
    var length = (keys || obj).length;
    var index = 0;
    var currentKey;
    
    func = iteratee(func, context);
    for (; index < length; index++) {
        currentKey = keys ? keys[index] : index;
        if (func(obj[currentKey], currentKey, obj)) return true;
    }
    return false;
};
var test = require('tape');
var some = require('./some');
var isObject = require('amp-is-object');
var isNumber = require('amp-is-number');


test('amp-some', function (t) {
    t.notOk(some([]), 'the empty set');
    t.notOk(some([false, false, false]), 'all false values');
    t.ok(some([false, false, true]), 'one true value');
    t.ok(some([null, 0, 'yes', false]), 'a string');
    t.notOk(some([null, 0, '', false]), 'falsy values');
    
    var isEven = function (num) {
        return num % 2 === 0;
    };

    t.notOk(some([1, 11, 29], isEven), 'all odd numbers');
    t.ok(some([1, 10, 29], isEven), 'an even number');
    
    var identity = function (val) {
        return val;
    };

    t.ok(some([1], identity) === true, 'cast to boolean - true');
    t.ok(some([0], identity) === false, 'cast to boolean - false');
    t.ok(some([false, false, true]));

    var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
    t.notOk(some(list, {a: 5, b: 2}), 'Can be called with object');
    t.ok(some(list, 'a'), 'String mapped to object property');

    list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}];
    t.ok(some(list, {b: 2}), 'Can be called with object');
    t.notOk(some(list, 'd'), 'String mapped to object property');

    t.ok(some({a: '1', b: '2', c: '3', d: '4', e: 6}, isNumber), 'takes objects');
    t.notOk(some({a: 1, b: 2, c: 3, d: 4}, isObject), 'takes objects');
    
    var hasProperty = function (value) {
        return !!this[value];
    };

    t.ok(some(['a', 'b', 'c', 'd'], hasProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works');
    t.notOk(some(['x', 'y', 'z'], hasProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works');
    t.end();
});

Estimated bundle size increase

~863 B (details)

Dependencies

amp-sort-by

amp-sort-by

v1.0.0

Lodash Version: lodash.sortby

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns a (stably) sorted copy of a collection, ranked in ascending order by the results of running each value through the iteratee you provide. That iteratee can also be the string name of the property to sort by (eg. length).

Example Usage

var sortBy = require('amp-sort-by');

//Sort by property
var array = [
    {id: 1, name: 'larry'},
    {id: 2, name: 'curly'},
    {id: 3, name: 'moe'}
];

sortBy(array, 'name');
//=> [ { id: 2, name: 'curly' }, { id: 1, name: 'larry' }, { id: 3, name: 'moe' } ]

//Sort by function

sortBy(array, function (item) {
    return item.name.length;
});
//=> [ { id: 3, name: 'moe' }, { id: 1, name: 'larry' }, { id: 2, name: 'curly' } ]


//Using context

var Collection = function () {
    this.sortAttribute = 'name';
    this.items = array;
};

var collection = new Collection();

sortBy(array, function (item) { return item[this.sortAttribute]; }, collection);
//=> [ { id: 2, name: 'curly' }, { id: 1, name: 'larry' }, { id: 3, name: 'moe' } ]
var iteratee = require('amp-iteratee');
var pluck = require('amp-pluck');
var map = require('amp-map');


module.exports = function sortBy(array, comparator, context) {
    comparator = iteratee(comparator, context);
    return pluck(map(array, function(value, index, list) {
      return {
        value: value,
        index: index,
        criteria: comparator(value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria;
      var b = right.criteria;
      if (a !== b) {
        if (a > b || a === void 0) return 1;
        if (a < b || b === void 0) return -1;
      }
      return left.index - right.index;
    }), 'value');
};
var test = require('tape');
var sortBy = require('./sort-by');
var pluck = require('amp-pluck');


test('amp-sort-by', function (t) {
    var people = [{name : 'curly', age : 50}, {name : 'moe', age : 30}];
    people = sortBy(people, function(person){ return person.age; });
    t.deepEqual(pluck(people, 'name'), ['moe', 'curly'], 'stooges sorted by age');

    // these is written this way because IE does weird things
    // with array literals that are declared with undefineds
    // [undefined, 4, 1, undefined, 3, 2]
    // [1, 2, 3, 4, undefined, undefined]
    var list = [];
    var expected = [];
    expected.push(1, 2, 3, 4, undefined, undefined);
    list.push(undefined, 4, 1, undefined, 3, 2);

    t.deepEqual(sortBy(list), expected, 'sortBy with undefined values');

    list = ['one', 'two', 'three', 'four', 'five'];
    var sorted = sortBy(list, 'length');
    t.deepEqual(sorted, ['one', 'two', 'four', 'five', 'three'], 'sorted by length');

    function Pair(x, y) {
        this.x = x;
        this.y = y;
    }

    var collection = [
        new Pair(1, 1), new Pair(1, 2),
        new Pair(1, 3), new Pair(1, 4),
        new Pair(1, 5), new Pair(1, 6),
        new Pair(2, 1), new Pair(2, 2),
        new Pair(2, 3), new Pair(2, 4),
        new Pair(2, 5), new Pair(2, 6),
        new Pair(undefined, 1), new Pair(undefined, 2),
        new Pair(undefined, 3), new Pair(undefined, 4),
        new Pair(undefined, 5), new Pair(undefined, 6)
    ];

    var actual = sortBy(collection, function(pair) {
        return pair.x;
    });

    t.deepEqual(actual, collection, 'sortBy should be stable');

    t.deepEqual(sortBy(collection, 'x'), collection, 'sortBy accepts property string');

    list = ['q', 'w', 'e', 'r', 't', 'y'];
    t.deepEqual(sortBy(list), ['e', 'q', 'r', 't', 'w', 'y'], 'uses identity if iterator is not specified');

    t.end();
});

Estimated bundle size increase

~1.01 kB (details)

Dependencies

amp-to-array

amp-to-array

v1.0.1

Lodash Version: lodash.toarray

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Creates a real Array from the list (anything that can be iterated over).

Example Usage

var toArray = require('amp-to-array');

(function(){ return toArray(arguments).slice(1); })(1, 2, 3, 4);// [2, 3, 4]
var values = require('amp-values');
var map = require('amp-map');
var isArray = require('amp-is-array');
var slice = Array.prototype.slice;
var identity = function (val) { return val; };


module.exports = function toArray(obj) {
    if (!obj) return [];
    if (isArray(obj)) return slice.call(obj);
    if (obj.length === +obj.length) return map(obj, identity);
    return values(obj);
};
var test = require('tape');
var toArray = require('./to-array');
var isArray = require('amp-is-array');


test('amp-to-array', function (t) {
    t.ok(!isArray(arguments), 'arguments object is not an array');
    t.ok(isArray(toArray(arguments)), 'arguments object converted into array');
    var a = [1, 2, 3];
    t.ok(toArray(a) !== a, 'array is cloned');
    t.deepEqual(toArray(a), [1, 2, 3], 'cloned array contains same elements');

    var numbers = toArray({one : 1, two : 2, three : 3});
    t.deepEqual(numbers, [1, 2, 3], 'object flattened into array');

    var fn = function () {
        t.deepEqual(toArray(arguments), [true], 'should convert args to arrays');
    };

    fn(true);

    t.end();
});

Estimated bundle size increase

~977 B (details)

Dependencies

amp-compact

amp-compact

v1.0.0

Lodash Version: lodash.compact

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns a copy of the array with all falsy values removed. This includes false, null, 0, "", undefined and NaN.

Example Usage

var compact = require('amp-compact');

console.log(contains([0, 1, false, 2, false, 3])); //=> [1, 2, 3]
var filter = require('amp-filter');
var identity = function (val) { return val; };


module.exports = function compact(arr) {
    return filter(arr, identity);
};
var test = require('tape');
var compact = require('./compact');


test('amp-compact', function (t) {
    t.equals(compact([0, 1, false, 2, false, 3]).length, 3, 'can trim out all falsy values');
    var result = (function(){ return compact(arguments).length; }(0, 1, false, 2, false, 3));
    t.equal(result, 3, 'works on an arguments object');
    t.end();
});
   

Estimated bundle size increase

~945 B (details)

Dependencies

amp-difference

amp-difference

v1.0.1

Lodash Version: lodash.difference

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns all the values from the array that are not present in any of the other arrays.

Example Usage

var difference = require('amp-difference');

difference([1, 2, 3, 4, 5], [1, 2]); //=> [3, 4, 5]

// can also pass multiple
difference([1, 2, 3, 4, 5], [1, 2], [3]); //=> [4, 5]
var filter = require('amp-filter');
var flatten = require('amp-internal-flatten');
var contains = require('amp-contains');


module.exports = function difference(array) {
    var rest = flatten(arguments, true, true, 1);
    return filter(array, function (value) {
        return !contains(rest, value);
    });
};
var test = require('tape');
var difference = require('./difference');


test('amp-difference', function (t) {
    var result = difference([1, 2, 3], [2, 30, 40]);
    t.deepEqual(result, [1, 3], 'takes the difference of two arrays');

    result = difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]);
    t.deepEqual(result, [3, 4], 'takes the difference of three arrays');

    result = difference([1, 2, 3], 1);
    t.deepEqual(result, [1, 2, 3], 'restrict the difference to arrays only');
    t.end();
});

Estimated bundle size increase

~1.25 kB (details)

Dependencies

amp-first

amp-first

v1.0.0

Lodash Version: lodash.first

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns the first item(s) in an array. Passing n will return the first n items in the array. Also works on arguments.

Example Usage

var first = require('amp-first');

first([1, 2, 3]); //=> 1
first([1, 2, 3], 2); //=> [1, 2]
var slice = Array.prototype.slice;


module.exports = function first(arr, n, guard) {
    if (arr == null) return void 0;
    if (n == null || guard) return arr[0];
    if (n < 0) return [];
    return slice.call(arr, 0, n);
};
var test = require('tape');
var first = require('./first');


test('amp-first', function (t) {
    t.equal(first([1, 2, 3]), 1, 'can pull out the first element of an array');
    t.deepEqual(first([1, 2, 3], 0), [], 'can pass an index to first');
    t.deepEqual(first([1, 2, 3], 2), [1, 2], 'can pass an index to first');
    t.deepEqual(first([1, 2, 3], 5), [1, 2, 3], 'can pass an index to first');
    var result = (function(){ return first(arguments); }(1, 2, 3, 4));
    t.equal(result, 1, 'works on an arguments object');
    if ([].map) {
        result = [[1, 2, 3], [1, 2, 3]].map(first);
        t.deepEqual(result, [1, 1], 'works well with map');
    }

    t.equal(first(null), undefined, 'handles nulls');
    t.strictEqual(first([1, 2, 3], -1).length, 0);
    t.end();
});

Estimated bundle size increase

~58 B (details)

Dependencies

(none)

none

amp-flatten

amp-flatten

v1.0.1

Lodash Version: lodash.flatten

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.

Example Usage

var flatten = require('amp-flatten');


flatten([1, [2], [3, [[4]]]]);
//=> [1, 2, 3, 4];

flatten([1, [2], [3, [[4]]]], true);
//=> [1, 2, 3, [[4]]];
var internalFlatten = require('amp-internal-flatten');


module.exports = function flatten(array, shallow) {
    return internalFlatten(array, shallow, false);
};
var test = require('tape');
var flatten = require('./flatten');
var range = require('amp-range');


test('amp-flatten', function (t) {
    t.deepEqual(flatten(null), [], 'Flattens supports null');
    t.deepEqual(flatten(void 0), [], 'Flattens supports undefined');

    t.deepEqual(flatten([[], [[]], []]), [], 'Flattens empty arrays');
    t.deepEqual(flatten([[], [[]], []], true), [[]], 'Flattens empty arrays');

    var list = [1, [2], [3, [[[4]]]]];
    t.deepEqual(flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');
    t.deepEqual(flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');
    var result = (function(){ return flatten(arguments); }(1, [2], [3, [[[4]]]]));
    t.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');
    list = [[1], [2], [3], [[4]]];
    t.deepEqual(flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');

    t.equal(flatten([range(10), range(10), 5, 1, 3], true).length, 23);
    t.equal(flatten([range(10), range(10), 5, 1, 3]).length, 23);
    t.equal(flatten([new Array(10000), range(5600), 5, 1, 3]).length, 15603, 'Flatten can handle massive collections');
    t.equal(flatten([new Array(10000), range(5600), 5, 1, 3], true).length, 15603, 'Flatten can handle massive collections');
    t.end();
});

Estimated bundle size increase

~299 B (details)

Dependencies

amp-index-of

amp-index-of

v1.1.0

Lodash Version: lodash.indexof

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns the index at which the item can be found in the array (also works for arguments object). Returns -1 if value is not present. Unlike native implementations this won't throw an error if passed something other than an array, it'll just return -1. You can optionally pass a fromIndex as the third argument to start the search there.

Example Usage

var indexOf = require('amp-index-of');

indexOf(['oh', 'hello', 'there'], 'hello'); //=> 1
indexOf(['hi', 'there'], 'hello'); //=> -1
var isNumber = require('amp-is-number');


module.exports = function indexOf(arr, item, from) {
    var i = 0;
    var l = arr && arr.length;
    if (isNumber(from)) {
        i = from < 0 ? Math.max(0, l + from) : from;
    }
    for (; i < l; i++) {
        if (arr[i] === item) return i;
    }
    return -1;
};
var test = require('tape');
var indexOf = require('./index-of');
var isArray = require('amp-is-array');
var each = require('amp-each');


test('amp-index-of', function (t) {
    var args = (function () { return arguments })('hi', 'there');
    t.equal(indexOf(args, 'there'), 1, 'works on `arguments` objects');
    t.equal(indexOf({'hi': 'hello'}, 'hi'), -1, 'returns `-1` if passed object');
    t.equal(indexOf(['a', 'b'], 1), -1);
    t.equal(indexOf(undefined, 1), -1);
    t.equal(indexOf(null, 1), -1);
    t.equal(indexOf(NaN, 1), -1);
    t.equal(indexOf({}, 1), -1);
    t.equal(indexOf(['a'], 'a'), 0);
    t.equal(indexOf(['a' , 1], 1), 1);
    
    each([null, void 0, [], false], function(val) {
        var msg = 'Handles: ' + (isArray(val) ? '[]' : val);
        t.equal(indexOf(val, 2), -1, msg);
        t.equal(indexOf(val, 2, -1), -1, msg);
        t.equal(indexOf(val, 2, -20), -1, msg);
        t.equal(indexOf(val, 2, 15), -1, msg);
    });

    var numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
    t.equal(indexOf(numbers, 2, 5), 7, 'supports the fromIndex argument');

    index = indexOf([,,,], undefined);
    t.equal(index, 0, 'treats sparse arrays as if they were dense');

    var array = [1, 2, 3, 1, 2, 3];
    t.strictEqual(indexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index');
    t.strictEqual(indexOf(array, 1, -2), -1, 'neg `fromIndex` starts at the right index');
    t.strictEqual(indexOf(array, 2, -3), 4);
    each([-6, -8, -Infinity], function(fromIndex) {
      t.strictEqual(indexOf(array, 1, fromIndex), 0);
    });
    t.strictEqual(indexOf([1, 2, 3], 1, true), 0);

    t.end();
});


Estimated bundle size increase

~130 B (details)

Dependencies

amp-intersection

amp-intersection

v1.0.0

Lodash Version: lodash.intersection

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Computes the list of values that are the intersection of all the arrays. Each value in the resulting array is present in each of the arrays.

Any items in the result will be in the same order as they were in the first array passed to intersection.

Example Usage

var intersection = require('amp-intersection');

intersection([1, 2, 3], [101, 2, 1, 10]);
//=> [1, 2]

//can take any number of arrays
intersection([1, 2, 3], [101, 2, 1, 10], [2, 1, 100]);
//=> [1, 2]
var contains = require('amp-contains');


module.exports = function intersection(array) {
    if (array == null) return [];
    var result = [];
    var argsLength = arguments.length;

    for (var i = 0, length = array.length; i < length; i++) {
        var item = array[i];
        if (contains(result, item)) continue;
        for (var j = 1; j < argsLength; j++) {
            if (!contains(arguments[j], item)) break;
        }
        if (j === argsLength) result.push(item);
    }
    return result;
};
var test = require('tape');
var intersection = require('./intersection');


test('amp-intersection', function (t) {
    var stooges = ['moe', 'curly', 'larry']
    var leaders = ['moe', 'groucho'];

    t.deepEqual(intersection(stooges, leaders), ['moe'], 'can take the set intersection of two arrays');

    var result = (function(){ return intersection(arguments, leaders); }('moe', 'curly', 'larry'));
    t.deepEqual(result, ['moe'], 'works on an arguments object');

    var theSixStooges = ['moe', 'moe', 'curly', 'curly', 'larry', 'larry'];
    t.deepEqual(intersection(theSixStooges, leaders), ['moe'], 'returns a duplicate-free array');

    result = intersection([2, 4, 3, 1], [1, 2, 3]);
    t.deepEqual(result, [2, 3, 1], 'preserves order of first array');

    result = intersection(null, [1, 2, 3]);
    t.equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as first argument');
    t.equal(result.length, 0, 'returns an empty array when passed null as first argument');

    result = intersection([1, 2, 3], null);
    t.equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as argument beyond the first');
    t.equal(result.length, 0, 'returns an empty array when passed null as argument beyond the first');

    t.end();
});

Estimated bundle size increase

~571 B (details)

Dependencies

amp-jump

amp-jump

v1.0.0

Docs

If you pass an array and an item in that array, returns the item immediately following that item.

Optionally, pass a number to specify how much to jump by (defaults to 1). This number can be positive or negative.

If item is not in array, returns undefined.

If you jump out of range, returns undefined unless you pass true as the loop argument. In which case it loops around to other end.

Example Usage

var jump = require('amp-jump');


var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

// basic case
jump(arr, 'a'); //=> 'b'
jump(arr, 'a', 3); //=> 'd'

// returns undefined if out of range
jump(arr, 'g'); //=> undefined

// negative jump values work fine
jump(arr, 'b', -1); //=> 'a'

// if you want to loop around, pass `true` as `loop` argument
jump(arr, 'a', -1, true); //=> 'g'
jump(arr, 'a', 7, true); //=> 'a'

// returns `undefined` if the item passed
// isn't found in the list at all
jump(arr, 'z'); //=> undefined
var isNumber = require('amp-is-number');
var isArray = require('amp-is-array');
var indexOf = require('amp-index-of');


module.exports = function jump(array, currentItem, jumpSize, loop) {
    if (!isArray(array)) return array;
    var index = indexOf(array, currentItem);
    if (index === -1) {
        return;
    }
    if (!isNumber(jumpSize)) {
        jumpSize = 1;
    }

    var len = array.length;    
    var newIndex = index + jumpSize;

    // we jumped too far
    if (newIndex > (len - 1)) {
        return loop ? array[newIndex % len] : undefined;
    }

    // we're negative
    if (newIndex < 0) {
        if (!loop) return;
        newIndex = len + (newIndex % len);
        if (newIndex === len) {
            newIndex = 0;
        }
    }

    // return our new item
    return array[newIndex];
};
var test = require('tape');
var jump = require('./jump');


test('amp-jump', function (t) {
    var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

    var obj = {};
    t.equal(jump(obj), obj, 'should return passed value for non arrays');
    t.equal(jump(1), 1, 'should return passed value for simple values');
    
    t.equal(jump(arr, 'x'), undefined, 'returns `undefined` if passed item not present');
    t.equal(jump(arr, 'a', -1), undefined, 'returns `undefined` if out of range low end');
    t.equal(jump(arr, 'a', 7), undefined, 'returns `undefined` if out of range on high end');

    t.equal(jump(arr, 'a'), 'b', '`jump` defaults to `1`');
    t.equal(jump(arr, 'a', 1), 'b', 'jumps work');
    t.equal(jump(arr, 'a', 3), 'd', 'jumps work');
    t.equal(jump(arr, 'c', -2), 'a', 'works for negative `jump`');

    // with loop argument
    t.equal(jump(arr, 'g', null, true), 'a', 'loops around to front if not given a jump');
    t.equal(jump(arr, 'g', 1, true), 'a', 'loops around to front');
    t.equal(jump(arr, 'g', 5, true), 'e', 'loops around to front with jumps');
    t.equal(jump(arr, 'g', 706, true), 'f', 'loops around to front with even larger jumps');
    
    t.equal(jump(arr, 'a', -1, true), 'g', 'loops around to back');
    t.equal(jump(arr, 'a', -5, true), 'c', 'loops around to back with slightly larger jumps');
    t.equal(jump(arr, 'a', -705, true), 'c', 'loops around to back with much larger jumps');
    
    t.equal(jump(arr, 'a', 0), 'a', 'should work for zero');
    t.equal(jump(arr, 'd', 0), 'd', 'should work for zero at any point');
    t.equal(jump(arr, 'g', 0), 'g', 'should work for zero at end');
    
    t.end();
});

Estimated bundle size increase

~284 B (details)

Dependencies

amp-last

amp-last

v1.0.1

Lodash Version: lodash.last

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns the last item(s) in an array. Passing n will return the last n items in the array. Also works on arguments.

Example Usage

var last = require('amp-last');

last([1, 2, 3]); //=> 3
last([1, 2, 3], 2); //=> [2, 3]
var slice = Array.prototype.slice;


module.exports = function last(arr, n, guard) {
    if (arr == null) return void 0;
    if (n == null || guard) return arr[arr.length - 1];
    return slice.call(arr, Math.max(0, arr.length - n));
};
var test = require('tape');
var last = require('./last');


test('amp-last', function (t) {
    t.equal(last([1, 2, 3]), 3, 'can pull out the last element of an array');
    t.deepEqual(last([1, 2, 3], 0), [], 'can pass an index to last');
    t.deepEqual(last([1, 2, 3], 2), [2, 3], 'can pass an index to last');
    t.deepEqual(last([1, 2, 3], 5), [1, 2, 3], 'can pass an index to last');
    var result = (function(){ return last(arguments); }(1, 2, 3, 4));
    t.equal(result, 4, 'works on an arguments object');
    if ([].map) {
        result = [[1, 2, 3], [1, 2, 3]].map(last);
        t.deepEqual(result, [3, 3], 'works well with map');
    }

    t.equal(last(null), undefined, 'handles nulls');
    t.strictEqual(last([1, 2, 3], -1).length, 0);
    t.end();
});

Estimated bundle size increase

~65 B (details)

Dependencies

(none)

none

amp-range

amp-range

v1.0.1

Lodash Version: lodash.range

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

A function to create numbered lists of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1. Returns an Array of integers from start to stop, incremented (or decremented) by step, exclusive.

Note that ranges that stop before they start are considered to be zero-length instead of negative — if you'd like a negative range, use a negative step.

Example Usage

var range = require('amp-range');


range(10); //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1, 11); //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(0, 30, 5); //=> [0, 5, 10, 15, 20, 25]
range(0, -10, -1); //=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
range(0); //=> []
module.exports = function range(start, stop, step) {
    if (arguments.length <= 1) {
        stop = start || 0;
        start = 0;
    }
    step = step || 1;

    var length = Math.max(Math.ceil((stop - start) / step), 0);
    var output = Array(length);

    for (var idx = 0; idx < length; idx++, start += step) {
        output[idx] = start;
    }

    return output;
};
var test = require('tape');
var range = require('./range');


test('amp-range', function (t) {
    t.deepEqual(range(0), [], 'range with 0 as a first argument generates an empty array');
    t.deepEqual(range(4), [0, 1, 2, 3], 'range with a single positive argument generates an array of elements 0,1,2,...,n-1');
    t.deepEqual(range(5, 8), [5, 6, 7], 'range with two arguments a &amp; b, a&lt;b generates an array of elements a,a+1,a+2,...,b-2,b-1');
    t.deepEqual(range(8, 5), [], 'range with two arguments a &amp; b, b&lt;a generates an empty array');
    t.deepEqual(range(3, 10, 3), [3, 6, 9], 'range with three arguments a &amp; b &amp; c, c &lt; b-a, a &lt; b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) &lt; c');
    t.deepEqual(range(3, 10, 15), [3], 'range with three arguments a &amp; b &amp; c, c &gt; b-a, a &lt; b generates an array with a single element, equal to a');
    t.deepEqual(range(12, 7, -2), [12, 10, 8], 'range with three arguments a &amp; b &amp; c, a &gt; b, c &lt; 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b');
    t.deepEqual(range(0, -10, -1), [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final example in the Python docs');
    t.end();
});

Estimated bundle size increase

~86 B (details)

Dependencies

(none)

none

amp-sorted-index

amp-sorted-index

v1.0.0

Lodash Version: lodash.sortedindex

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Find the smallest index at which an object should be inserted so as to maintain sort order using a binary search.

Sorting is done either by raw comparison (<, >, =) on each item, or via an optional comparator. You can also optionally give a context to the comparator.

Example Usage

var sortedIndex = require('amp-sorted-index');

//Using native compare
var items = [1,3,5,7]; //Already sorted
sortedIndex(items, 2); //=> 1

//Using string comparator
var people = [
    {name: 'Robert', rank: 2},
    {name: 'Sally', rank: 4}
]; //Already sorted by rank

var pat = {name: 'Pat', rank: 1};

sortedIndex(people, pat, 'rank'); //=> 0

//Using function comparator
function nameLength(person) {
    return person.name.length;
}

var people = [
    {name: 'Pat', rank: 1},
    {name: 'Robert', rank: 2}
]; //Already sorted by name length

var sally = {name: 'Sally', rank: 4};

sortedIndex(people, sally, nameLength); //=> 2
var iteratee = require('amp-iteratee');


module.exports = function sortedIndex(array, obj, comparator, context) {
    comparator = iteratee(comparator, context, 1);
    var value = comparator(obj);
    var low = 0, high = array.length;
    while (low < high) {
        var mid = Math.floor((low + high) / 2);
        if (comparator(array[mid]) < value) low = mid + 1; else high = mid;
    }
    return low;
};
var test = require('tape');
var sortedIndex = require('./sorted-index');


test('amp-sorted-index', function (t) {
    var numbers = [10, 20, 30, 40, 50], num = 35;
    var indexForNum = sortedIndex(numbers, num);
    t.equal(indexForNum, 3, '35 should be inserted at index 3');

    var indexFor30 = sortedIndex(numbers, 30);
    t.equal(indexFor30, 2, '30 should be inserted at index 2');

    var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];
    var iterator = function(obj){ return obj.x; };
    t.strictEqual(sortedIndex(objects, {x: 25}, iterator), 2);
    t.strictEqual(sortedIndex(objects, {x: 35}, 'x'), 3);

    var context = {1: 2, 2: 3, 3: 4};
    iterator = function(obj){ return this[obj]; };
    t.strictEqual(sortedIndex([1, 3], 2, iterator, context), 1);

    var values = [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215, 33554431, 67108863, 134217727, 268435455, 536870911, 1073741823, 2147483647];
    var array = Array(Math.pow(2, 32) - 1);
    var length = values.length;
    while (length--) {
        array[values[length]] = values[length];
    }
    t.equal(sortedIndex(array, 2147483648), 2147483648, 'should work with large indexes');
    t.end();
});

Estimated bundle size increase

~853 B (details)

Dependencies

amp-sorted-insert

amp-sorted-insert

v1.0.0

Docs

Inserts an item onto an already sorted array (or array-like object) in a way that leaves the array sorted and returns the index at which the new item was inserted.

Uses a binary search using the new item and the items in the array to determine where to put the new item.

Sorting is done either by raw comparison (<, >, =) or via a comparator which can be a string representing a named attribute of the itme, or a function that will be given one item and will return the value to be used in comparisons.

Example Usage

var sortedInsert = require('amp-sorted-insert');

//Using native compare
var items = [1,3,5,7]; //Already sorted
sortedInsert(items, 2); //[1,2,3,5,7]


//Using string comparator
var people = [
    {name: 'Robert', rank: 2},
    {name: 'Sally', rank: 4}
]; //Already sorted by rank

var pat = {name: 'Pat', rank: 1};

sortedInsert(people, pat, 'rank'); //[{name: 'Pat', rank:1}, {name: 'Robert', rank: 2}, {name: 'Sally', rank: 4}]


//Using function comparator
function nameLength(person) {
    return person.name.length;
}

var people = [
    {name: 'Pat', rank: 1},
    {name: 'Robert', rank: 2}
]; //Already sorted by name length

var sally = {name: 'Sally', rank: 4};

sortedInsert(people, sally, nameLength); //[{name: 'Pat', rank: 1}, {name: 'Sally', rank: 4}, {name: 'Robert', rank: 2}]
var sortedIndex = require('amp-sorted-index');
var splice = Array.prototype.splice;


module.exports = function sortedInsert(array, item) {
    var index = sortedIndex.apply(this, arguments);
    splice.call(array, index, 0, item);
    return index;
};
var test = require('tape');
var sortedInsert = require('./sorted-insert');


test('amp-sorted-insert', function (t) {
    var numbers = [1,3,5,7];
    sortedInsert(numbers, 2);
    t.equal(numbers.length, 5);
    t.equal(numbers[1], 2);

    var robert = {name: 'Robert', rank: 2};
    var sally = {name: 'Sally', rank: 4};
    var pat = {name: 'Pat', rank: 1};
    var people = [robert, sally];
    
    sortedInsert(people, pat, 'rank');
    t.deepEqual(people, [pat, robert, sally]);

    people = [pat, robert];
    sortedInsert(people, sally, function (person) { return person.name.length; });
    t.deepEqual(people, [pat, sally, robert]);

    var arrayLike = {
        0: 'a',
        1: 'b',
        length: 2
    };
    var index = sortedInsert(arrayLike, 'c');
    t.equal(index, 2, 'should be inserted at 2');
    t.deepEqual(arrayLike, {
        0: 'a',
        1: 'b',
        2: 'c',
        length: 3
    }, 'should modify array-like object');

    t.end();
});

Estimated bundle size increase

~905 B (details)

Dependencies

amp-union

amp-union

v1.0.0

Lodash Version: lodash.union

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

Example Usage

var union = require('amp-union');

union([1, 2, 3], [101, 2, 1, 10]);
//=> [1, 2, 3, 101, 10]

//can take any number of arrays
union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
//=> [1, 2, 3, 101, 10]
var flatten = require('amp-internal-flatten');
var unique = require('amp-unique');


module.exports = function union() {
    return unique(flatten(arguments, true, true));
};
var test = require('tape');
var union = require('./union');


test('amp-union', function (t) {
    var result = union([1, 2, 3], [2, 30, 1], [1, 40]);
    t.deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays');

    result = union([1, 2, 3], [2, 30, 1], [1, 40, [1]]);
    t.deepEqual(result, [1, 2, 3, 30, 40, [1]], 'takes the union of a list of nested arrays');

    var args = null;
    (function(){ args = arguments; }(1, 2, 3));
    result = union(args, [2, 30, 1], [1, 40]);
    t.deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays');

    result = union([1, 2, 3], 4);
    t.deepEqual(result, [1, 2, 3], 'restrict the union to arrays only');

    t.end();
});

Estimated bundle size increase

~1.27 kB (details)

Dependencies

amp-unique

amp-unique

v1.0.1

Lodash Version: lodash.uniq

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Produces a duplicate-free version of the array, (using === to test object equality, by default).

If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm.

If you want to compute unique items based on a transformation, pass an iteratee function. If said iteratee requires custom context, you can pass that as the last argument.

Example Usage

var unique = require('amp-unique');

unique([1, 4, 2, 4, 3]); //=> [1, 4, 2, 3]

// if sorted, you can speed things up
unique([1, 1, 2, 3, 4, 4, 5], true); //=> [1, 2, 3, 4, 5]

// getting unique objects checking a property value in list
// of objects also works
var people = [
    {name: 'sue'},
    {name: 'max'},
    {name: 'sue'}
};

// can just pass name of property as string
unique(people, 'name');
//=> [
//=>   {name: 'sue'},
//=>   {name: 'max'}
//=> ]

// You can use your own iterator, just return
// value to use to check uniqueness
unique(people, function (person) {
    return person.name;
});
//=> [
//=>   {name: 'sue'},
//=>   {name: 'max'}
//=> ]
var isBoolean = require('amp-is-boolean');
var contains = require('amp-contains');
var getIteratee = require('amp-iteratee');


module.exports = function unique(array, isSorted, iteratee, context) {
    if (array == null) return [];
    if (!isBoolean(isSorted)) {
        context = iteratee;
        iteratee = isSorted;
        isSorted = false;
    }
    if (iteratee != null) iteratee = getIteratee(iteratee, context);
    var result = [];
    var seen = [];
    for (var i = 0, length = array.length; i < length; i++) {
        var value = array[i];
        var computed = iteratee ? iteratee(value, i, array) : value;
        if (isSorted) {
            if (!i || seen !== computed) result.push(value);
            seen = computed;
        } else if (iteratee) {
            if (!contains(seen, computed)) {
                seen.push(computed);
                result.push(value);
            }
        } else if (!contains(result, value)) {
            result.push(value);
        }
    }
    return result;
};
var test = require('tape');
var unique = require('./unique');
var map = require('amp-map');


test('amp-unique', function (t) {
    var list = [1, 2, 1, 3, 1, 4];
    t.deepEqual(unique(list), [1, 2, 3, 4], 'can find the unique values of an unsorted array');

    list = [1, 1, 1, 2, 2, 3];
    t.deepEqual(unique(list, true), [1, 2, 3], 'can find the unique values of a sorted array faster');

    list = [{name: 'moe'}, {name: 'curly'}, {name: 'larry'}, {name: 'curly'}];
    var iterator = function(value) { return value.name; };
    t.deepEqual(map(unique(list, false, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator');

    t.deepEqual(map(unique(list, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator without specifying whether array is sorted');

    iterator = function(value) { return value + 1; };
    list = [1, 2, 2, 3, 4, 4];
    t.deepEqual(unique(list, true, iterator), [1, 2, 3, 4], 'iterator works with sorted array');

    var kittens = [
        {kitten: 'Celery', cuteness: 8},
        {kitten: 'Juniper', cuteness: 10},
        {kitten: 'Spottis', cuteness: 10}
    ];

    var expected = [
        {kitten: 'Celery', cuteness: 8},
        {kitten: 'Juniper', cuteness: 10}
    ];

    t.deepEqual(unique(kittens, true, 'cuteness'), expected, 'string iterator works with sorted array');


    var result = (function(){ return unique(arguments); }(1, 2, 1, 3, 1, 4));
    t.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');

    var a = {}, b = {}, c = {};
    t.deepEqual(unique([a, b, a, b, c]), [a, b, c], 'works on values that can be tested for equivalency but not ordered');

    t.deepEqual(unique(null), []);

    var context = {};
    list = [3];
    unique(list, function(value, index, array) {
        t.strictEqual(this, context);
        t.strictEqual(value, 3);
        t.strictEqual(index, 0);
        t.strictEqual(array, list);
    }, context);

    t.deepEqual(unique([{a: 1, b: 1}, {a: 1, b: 2}, {a: 1, b: 3}, {a: 2, b: 1}], 'a'), [{a: 1, b: 1}, {a: 2, b: 1}], 'can use pluck like iterator');
    t.deepEqual(unique([{0: 1, b: 1}, {0: 1, b: 2}, {0: 1, b: 3}, {0: 2, b: 1}], 0), [{0: 1, b: 1}, {0: 2, b: 1}], 'can use falsey pluck like iterator');
    t.end();
});

Estimated bundle size increase

~1.01 kB (details)

Dependencies

amp-clone

amp-clone

v1.0.1

Lodash Version: lodash.clone

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.

Example Usage

var clone = require('amp-clone');

var original = {name: 'henrik'};
var copy = clone(original); //=> {name: 'henrik'}
console.log(original === copy); //=> false

var array = ['hi', 'there'];
var copied = clone(array); //=> ['hi', 'there']
console.log(array === copied); //=> false
var isObject = require('amp-is-object');
var isArray = require('amp-is-array');
var extend = require('amp-extend');


module.exports = function clone(obj) {
    if (!isObject(obj)) return obj;
    return isArray(obj) ? obj.slice() : extend({}, obj);
};
var test = require('tape');
var clone = require('./clone');


test('amp-clone', function (t) {
    var moe = {name : 'moe', lucky : [13, 27, 34]};
    var moeClone = clone(moe);
    t.equal(moeClone.name, 'moe', 'the clone as the attributes of the original');

    moeClone.name = 'curly';
    t.ok(moeClone.name === 'curly' && moe.name === 'moe', 'clones can change shallow attributes without affecting the original');

    moeClone.lucky.push(101);
    t.equal(moe.lucky[moe.lucky.length - 1], 101, 'changes to deep attributes are shared with the original');

    t.equal(clone(undefined), void 0, 'non objects should not be changed by clone');
    t.equal(clone(1), 1, 'non objects should not be changed by clone');
    t.equal(clone(null), null, 'non objects should not be changed by clone');
    t.end();
});

Estimated bundle size increase

~219 B (details)

Dependencies

amp-defaults

amp-defaults

v1.0.1

Lodash Version: lodash.defaults

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Fills in undefined properties in the first object with the first value present in the passed list of defaults objects.

A bit like extend except it's used to "fill in gaps" in first object with your defaults.

Returns the modified first object.

Example Usage

var defaults = require('amp-defaults');

var person = {
    name: 'Joe',
    favoriteColor: 'blue'
};

defaults(person, {
    height: 'unknown',
    age: 'unknown'
});

console.log(person);
//=>
// {
//   name: 'Joe',
//   favoriteColor: 'blue',
//   height: 'unknown',
//   age: 'unknown'
// }
var isObject = require('amp-is-object');


module.exports = function defaults(obj) {
    if (!isObject(obj)) return obj;
    for (var i = 1, length = arguments.length; i < length; i++) {
        var source = arguments[i];
        for (var prop in source) {
            if (obj[prop] === void 0) obj[prop] = source[prop];
        }
    }
    return obj;
};
var test = require('tape');
var defaults = require('./defaults');


test('amp-defaults', function (t) {
    var options = {zero: 0, one: 1, empty: '', nan: NaN, nothing: null};

    defaults(options, {zero: 1, one: 10, twenty: 20, nothing: 'str'});
    t.equal(options.zero, 0, 'value exists');
    t.equal(options.one, 1, 'value exists');
    t.equal(options.twenty, 20, 'default applied');
    t.equal(options.nothing, null, "null isn't overridden");

    defaults(options, {empty: 'full'}, {nan: 'nan'}, {word: 'word'}, {word: 'dog'});
    t.equal(options.empty, '', 'value exists');
    t.ok(isNaN(options.nan), "NaN isn't overridden");
    t.equal(options.word, 'word', 'new value is added, first one wins');

    try {
      options = {};
      defaults(options, null, undefined, {a: 1});
    } catch(ex) {}

    t.equal(options.a, 1, 'should not error on `null` or `undefined` sources');

    t.strictEqual(defaults(null, {a: 1}), null, 'result is null if destination is null');
    t.strictEqual(defaults(undefined, {a: 1}), undefined, 'result is undefined if destination is undefined');
    t.end();
});

Estimated bundle size increase

~118 B (details)

Dependencies

amp-extend

amp-extend

v1.0.1

Lodash Version: lodash.assign

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Copy all of the properties in the source objects over to the destination object, and return the destination object. This is done in order, so the last source will override properties of the same name in previous arguments.

Note that this is a shallow copy, meaning that nested objects won't be merged or extended.

Example Usage

var extend = require('amp-extend');

var person = {
    nickname: 'The Swede'
};

var attributes = {
    greeting: 'Oh, hello there!'
};

var preferences = {
    food: 'Swedish Fish'
};

extend(person, attributes, preferences);
//=> 
// {
//   nickname: 'The Swede',
//   greeting: 'Oh, hello there!',
//   food: 'Swedish Fish'
// }
var isObject = require('amp-is-object');


module.exports = function(obj) {
    if (!isObject(obj)) return obj;
    var source, prop;
    for (var i = 1, length = arguments.length; i < length; i++) {
        source = arguments[i];
        for (prop in source) {
            obj[prop] = source[prop];
        }
    }
    return obj;
};
var test = require('tape');
var extend = require('./extend');
var keys = require('amp-keys');


test('amp-extend', function(t) {
    var result;
    t.equal(extend({}, {a: 'b'}).a, 'b', 'can extend an object with the attributes of another');
    t.equal(extend({a: 'x'}, {a: 'b'}).a, 'b', 'properties in source override destination');
    t.equal(extend({x: 'x'}, {a: 'b'}).x, 'x', "properties not in source don't get overriden");
    result = extend({x: 'x'}, {a: 'a'}, {b: 'b'});
    t.deepEqual(result, {x: 'x', a: 'a', b: 'b'}, 'can extend from multiple source objects');
    result = extend({x: 'x'}, {a: 'a', x: 2}, {a: 'b'});
    t.deepEqual(result, {x: 2, a: 'b'}, 'extending from multiple source objects last property trumps');
    result = extend({}, {a: void 0, b: null});
    t.deepEqual(keys(result), ['a', 'b'], 'extend copies undefined values');

    var F = function() {};
    F.prototype = {a: 'b'};
    var subObj = new F();
    subObj.c = 'd';
    t.deepEqual(extend({}, subObj), {a: 'b', c: 'd'}, 'extend copies all properties from source');

    try {
      result = {};
      extend(result, null, undefined, {a: 1});
    } catch(ex) {}

    t.equal(result.a, 1, 'should not error on `null` or `undefined` sources');

    t.strictEqual(extend(null, {a: 1}), null, 'extending null results in null');
    t.strictEqual(extend(undefined, {a: 1}), undefined, 'extending undefined results in undefined');
    t.end();
});

Estimated bundle size increase

~111 B (details)

Dependencies

amp-has

amp-has

v1.0.1

Lodash Version: lodash.has

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if the object contains the given key, false otherwise. Identical to object.hasOwnProperty(key), but uses Object.prototype.hasOwnProperty directly in case it's been overridden on the object itself.

Also, protects against some obscure quirks with enumerable built-ins in IE < 9.

Example Usage

var has = require('amp-has');

var obj = {
    greeting: 'Oh, hello there!'
};

has(obj, 'greeting'); //=> true
has(obj, 'hasOwnProperty'); //=> false
var hasOwn = Object.prototype.hasOwnProperty;


module.exports = function has(obj, key) {
    return obj != null && hasOwn.call(obj, key);
};
var test = require('tape');
var has = require('./has');


test('amp-has', function (t) {
    t.ok(has({'hi': 'thing'}, 'hi'));
    t.ok(!has({'hi': 'thing'}, 'hasOwnProperty'));
    t.ok(!has(['a', 'b'], 'a'));
    t.ok(!has(undefined, 1));
    t.ok(!has(null, 1));
    t.ok(!has(NaN, 1));
    t.end();
});

Estimated bundle size increase

~43 B (details)

Dependencies

(none)

none

amp-invert

amp-invert

v1.0.1

Lodash Version: lodash.invert

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns a copy of the object where the keys have become the values and the values the keys. Your object's values should be unique and string serializable (a.k.a. JSON.stringify-able). If the values are not unique, inverting it would squash some keys, since keys in an object have to be unique.

Example Usage

var invert = require('amp-invert');

var person = {
    favoriteColor: 'magenta',
    favoriteFood: 'swedish pancakes'
};

invert(person);
//=> 
// { 
//   magenta: 'favoriteColor',
//   'swedish pancakes': 'favoriteFood'
// }
var objKeys = require('amp-keys');


module.exports = function invert(obj) {
    var result = {};
    var keys = objKeys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
        result[obj[keys[i]]] = keys[i];
    }
    return result;
};
var test = require('tape');
var invert = require('./invert');
var keys = require('amp-keys');


test('amp-invert', function (t) {
    var obj = {first: 'Moe', second: 'Larry', third: 'Curly'};
    t.deepEqual(keys(invert(obj)), ['Moe', 'Larry', 'Curly'], 'can invert an object');
    t.deepEqual(invert(invert(obj)), obj, 'two inverts gets you back where you started');

    obj = {length: 3};
    t.equal(invert(obj)['3'], 'length', 'can invert an object with "length"');
    t.end();
});

Estimated bundle size increase

~429 B (details)

Dependencies

amp-keys

amp-keys

v1.0.1

Lodash Version: lodash.keys

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Retrieve all the names of the object's properties. This is much like Object.keys (in fact just uses it if it exists). But there's with one difference, you can pass a non-object and it won't throw an error. It will always return an array. So any non-objects passed will just return [].

Example Usage

var keys = require('amp-keys');

var obj = {
    hi: 'there',
    oh: 'hello there'
};

keys(obj); //=> ['hi', 'oh']
keys(undefined) //=> []
var has = require('amp-has');
var indexOf = require('amp-index-of');
var isObject = require('amp-is-object');
var nativeKeys = Object.keys;
var hasEnumBug = !({toString: null}).propertyIsEnumerable('toString');
var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];


module.exports = function keys(obj) {
    if (!isObject(obj)) return [];
    if (nativeKeys) {
        return nativeKeys(obj);
    }
    var result = [];
    for (var key in obj) if (has(obj, key)) result.push(key);
    // IE < 9
    if (hasEnumBug) {
        var nonEnumIdx = nonEnumerableProps.length;
        while (nonEnumIdx--) {
            var prop = nonEnumerableProps[nonEnumIdx];
            if (has(obj, prop) && indexOf(result, prop) === -1) result.push(prop);
        }
    }
    return result;
};
var test = require('tape');
var keys = require('./keys');


test('amp-keys', function (t) {
    t.deepEqual(keys({one : 1, two : 2}), ['one', 'two'], 'can extract the keys from an object');
    // the test above is not safe because it relies on for-in enumeration order
    var a = []; a[1] = 0;
    t.deepEqual(keys(a), ['1'], 'is not fooled by sparse arrays; see issue #95');
    t.deepEqual(keys(null), []);
    t.deepEqual(keys(void 0), []);
    t.deepEqual(keys(1), []);
    t.deepEqual(keys('a'), []);
    t.deepEqual(keys(true), []);

    // keys that may be missed if the implementation isn't careful
    var trouble = {
      'constructor': Object,
      'valueOf': function () {},
      'hasOwnProperty': null,
      'toString': 5,
      'toLocaleString': undefined,
      'propertyIsEnumerable': /a/,
      'isPrototypeOf': this,
      '__defineGetter__': Boolean,
      '__defineSetter__': {},
      '__lookupSetter__': false,
      '__lookupGetter__': []
    };
    var troubleKeys = ['constructor', 'valueOf', 'hasOwnProperty', 'toString', 'toLocaleString', 'propertyIsEnumerable',
                  'isPrototypeOf', '__defineGetter__', '__defineSetter__', '__lookupSetter__', '__lookupGetter__'].sort();
    t.deepEqual(keys(trouble).sort(), troubleKeys, 'matches non-enumerable properties');
    t.end();
});

Estimated bundle size increase

~383 B (details)

Dependencies

amp-matches

amp-matches

v1.0.1

Lodash Version: lodash.matches

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns a function that will tell you if a passed in object contains all of the key/value properties present in passed attributeObject.

Example Usage

var matches = require('amp-matches');
var filter = require('amp-filter');

var list = [
    {name: 'Someone', awesome: false},
    {name: 'Someone Else', awesome: true},
    {name: 'Paul Irish', awesome: true}
];
var awesomenessChecker = matches({awesome: true});
var awesomePeople = filter(list, awesomenessChecker);

console.log(awesomePeople);
//=> [
//=>    {name: 'Someone Else', awesome: true},
//=>    {name: 'Paul Irish', awesome: true}
//=> ]

var getPairs = require('amp-pairs');


module.exports = function matches(attrs) {
    var pairs = getPairs(attrs);
    var length = pairs.length;
    return function(obj) {
        if (obj == null) return !length;
        obj = new Object(obj);
        for (var i = 0; i < length; i++) {
            var pair = pairs[i], key = pair[0];
            if (pair[1] !== obj[key] || !(key in obj)) return false;
        }
        return true;
    };
};
var test = require('tape');
var matches = require('./matches');
var map = require('amp-map');


test('amp-matches', function (t) {
    var moe = {name: 'Moe Howard', hair: true};
    var curly = {name: 'Curly Howard', hair: false};
    var stooges = [moe, curly];

    t.equal(matches({hair: true})(moe), true, 'Returns a boolean');
    t.equal(matches({hair: true})(curly), false, 'Returns a boolean');

    t.equal(matches({__x__: undefined})(5), false, 'can match undefined props on primitives');
    t.equal(matches({__x__: undefined})({__x__: undefined}), true, 'can match undefined props');

    t.equal(matches({})(null), true, 'Empty spec called with null object returns true');
    t.equal(matches({a: 1})(null), false, 'Non-empty spec called with null object returns false');

    /* TODO 
    t.ok(_.find(stooges, matches({hair: false})) === curly, 'returns a predicate that can be used by finding functions.');
    t.ok(_.find(stooges, matches(moe)) === moe, 'can be used to locate an object exists in a collection.');
    t.deepEqual(_.where([null, undefined], {a: 1}), [], 'Do not throw on null values.');

    t.deepEqual(_.where([null, undefined], null), [null, undefined], 'null matches null');
    t.deepEqual(_.where([null, undefined], {}), [null, undefined], 'null matches {}');
    t.deepEqual(_.where([{b: 1}], {a: undefined}), [], 'handles undefined values (1683)');

    _.each([true, 5, NaN, null, undefined], function(item) {
        t.deepEqual(_.where([{a: 1}], item), [{a: 1}], 'treats primitives as empty');
    });
    */

    function Prototest() {}
    Prototest.prototype.x = 1;
    var specObj = new Prototest;
    var protospec = matches(specObj);
    t.equal(protospec({x: 2}), true, 'spec is restricted to own properties');

    specObj.y = 5;
    protospec = matches(specObj);
    t.equal(protospec({x: 1, y: 5}), true);
    t.equal(protospec({x: 1, y: 4}), false);

    t.ok(matches({x: 1, y: 5})(specObj), 'inherited and own properties are checked on the test object');

    Prototest.x = 5;
    t.ok(matches(Prototest)({x: 5, y: 1}), 'spec can be a function');

    // #1729
    var o = {'b': 1};
    var m = matches(o);

    t.equal(m({'b': 1}), true);
    o.b = 2;
    o.a = 1;
    t.equal(m({'b': 1}), true, 'changing spec object doesnt change matches result');


    //null edge cases
    var oCon = matches({'constructor': Object});
    t.deepEqual(map([null, undefined, 5, {}], oCon), [false, false, false, true], 'doesnt fasley match constructor on undefined/null');
    t.end();
});

Estimated bundle size increase

~520 B (details)

Dependencies

amp-merge

amp-merge

v1.0.0

Lodash Version: lodash.merge

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Merge source objects together and return a new object. This is done in order, so the last source will override properties of the same name in previous arguments.

Note that this is a shallow copy, meaning that nested objects won't be merged or extended.

Example Usage

var merge = require('amp-merge');

var person = {
  nickname: 'The Swede'
};

var attributes = {
  greeting: 'Oh, hello there!'
};

var preferences = {
  food: 'Swedish Fish'
};

merge(person, attributes, preferences);
//=>
// {
//   nickname: 'The Swede',
//   greeting: 'Oh, hello there!',
//   food: 'Swedish Fish'
// }
var extend = require('amp-extend');

module.exports = function merge() {
    var args = [].slice.call(arguments);
    args.unshift({});
    return extend.apply(this, args);
};
var test = require('tape');
var merge = require('./merge');
var keys = require('amp-keys');

test('amp-merge', function (t) {
    var result;
    var obj = {
        test: 'test',
        beep: 'boop'
    };

    t.deepEqual(merge(obj, {a: 'b'}), { a: 'b', beep: 'boop', test: 'test' }, 'can merge an object with the attributes of another');
    t.deepEqual(obj, { test: 'test', beep: 'boop' }, 'check that obj remains unchanged');

    t.equal(merge({a: 'x'}, {a: 'b'}).a, 'b', 'properties in source override destination');
    t.equal(merge({x: 'x'}, {a: 'b'}).x, 'x', "properties not in source don't get overridden");
    result = merge({x: 'x'}, {a: 'a'}, {b: 'b'});
    t.deepEqual(result, {x: 'x', a: 'a', b: 'b'}, 'can merge from multiple source objects');
    result = merge({x: 'x'}, {a: 'a', x: 2}, {a: 'b'});
    t.deepEqual(result, {x: 2, a: 'b'}, 'merge from multiple source objects last property trumps');
    result = merge({}, {a: void 0, b: null});
    t.deepEqual(keys(result), ['a', 'b'], 'merge copies undefined values');

    var F = function() {};
    F.prototype = {a: 'b'};
    var subObj = new F();
    subObj.c = 'd';
    t.deepEqual(merge({}, subObj), {a: 'b', c: 'd'}, 'merge copies all properties from source');

    t.deepEqual(merge(null, {a: 1}), { a: 1 }, 'will allow a parameter to be null');
    t.deepEqual(merge(undefined, {a: 1}), { a: 1 }, 'will allow a parameter to be null undefined');

    t.end();
});

Estimated bundle size increase

~166 B (details)

Dependencies

amp-omit

amp-omit

v1.0.0

Lodash Version: lodash.omit

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.

Example Usage

var omit = require('amp-omit');
var isNumber = require('amp-is-number');


omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid'); //=> {name: 'moe', age: 50}

omit({name: 'moe', age: 50, userid: 'moe1'}, function(value) {
    return isNumber(value);
}); //=> {name: 'moe', userid: 'moe1'}
var flatten = require('amp-internal-flatten');
var isFunction = require('amp-is-function');
var contains = require('amp-contains');
var negate = require('amp-negate');
var pick = require('amp-pick');
var map = require('amp-map');


module.exports = function omit(obj, iteratee, context) {
    if (isFunction(iteratee)) {
        iteratee = negate(iteratee);
    } else {
        var keys = map(flatten(arguments, false, false, 1), String);
        iteratee = function(value, key) {
            return !contains(keys, key);
        };
    }
    return pick(obj, iteratee, context);
};
var test = require('tape');
var omit = require('./omit');


test('amp-omit', function (t) {
    var result;
    result = omit({a: 1, b: 2, c: 3}, 'b');
    t.deepEqual(result, {a: 1, c: 3}, 'can omit a single named property');
    result = omit({a: 1, b: 2, c: 3}, 'a', 'c');
    t.deepEqual(result, {b: 2}, 'can omit several named properties');
    result = omit({a: 1, b: 2, c: 3}, ['b', 'c']);
    t.deepEqual(result, {a: 1}, 'can omit properties named in an array');
    result = omit(['a', 'b'], 0);
    t.deepEqual(result, {1: 'b'}, 'can omit numeric properties');

    t.deepEqual(omit(null, 'a', 'b'), {}, 'non objects return empty object');
    t.deepEqual(omit(undefined, 'toString'), {}, 'null/undefined return empty object');
    t.deepEqual(omit(5, 'toString', 'b'), {}, 'returns empty object for primitives');

    var data = {a: 1, b: 2, c: 3};
    var callback = function(value, key, object) {
        t.strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]);
        t.strictEqual(object, data);
        return value !== this.value;
    };
    result = omit(data, callback, {value: 2});
    t.deepEqual(result, {b: 2}, 'can accept a predicate');

    var Obj = function(){};
    Obj.prototype = {a: 1, b: 2, c: 3};
    var instance = new Obj();
    t.deepEqual(omit(instance, 'b'), {a: 1, c: 3}, 'include prototype props');

    t.deepEqual(omit(data, function(val, key) {
        return this[key] === 3 && this === instance;
    }, instance), {a: 1, b: 2}, 'function is given context');
    t.end();
});

Estimated bundle size increase

~1.35 kB (details)

Dependencies

amp-pairs

amp-pairs

v1.0.1

Lodash Version: lodash.pairs

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Convert an object into a list of [key, value] pairs.

Example Usage

var pairs = require('amp-pairs');

var obj = {one: 1, two: 2, three: 3};

pairs(obj); //=> [["one", 1], ["two", 2], ["three", 3]]
var objKeys = require('amp-keys');


module.exports = function pairs(obj) {
    var keys = objKeys(obj);
    var length = keys.length;
    var result = Array(length);
    for (var i = 0; i < length; i++) {
        result[i] = [keys[i], obj[keys[i]]];
    }
    return result;
};
var test = require('tape');
var pairs = require('./pairs');


test('amp-pairs', function (t) {
    t.deepEqual(pairs({one: 1, two: 2, three: 3}), [['one', 1], ['two', 2], ['three', 3]]);
    t.end();
});

Estimated bundle size increase

~442 B (details)

Dependencies

amp-pick

amp-pick

v1.0.0

Lodash Version: lodash.pick

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

Example Usage

var pick = require('amp-pick');
var isNumber = require('amp-is-number');

pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age'); //=> {name: 'moe', age: 50}

pick({name: 'moe', age: 50, userid: 'moe1'}, function (value, key, object) {
    return isNumber(value);
}); //=> {age: 50}
var createCallback = require('amp-create-callback');
var isFunction = require('amp-is-function');
var flatten = require('amp-internal-flatten');


module.exports = function pick(obj, iteratee, context) {
    var result = {}, key;
    if (obj == null) return result;
    if (isFunction(iteratee)) {
        iteratee = createCallback(iteratee, context);
        for (key in obj) {
            var value = obj[key];
            if (iteratee(value, key, obj)) result[key] = value;
        }
    } else {
        var keys = flatten(arguments, false, false, 1);
        obj = new Object(obj);
        for (var i = 0, length = keys.length; i < length; i++) {
            key = keys[i];
            if (key in obj) result[key] = obj[key];
        }
    }
    return result;
};
var test = require('tape');
var pick = require('./pick');


test('amp-pick', function (t) {
    var result;
    result = pick({a: 1, b: 2, c: 3}, 'a', 'c');
    t.deepEqual(result, {a: 1, c: 3}, 'can restrict properties to those named');
    result = pick({a: 1, b: 2, c: 3}, ['b', 'c']);
    t.deepEqual(result, {b: 2, c: 3}, 'can restrict properties to those named in an array');
    result = pick({a: 1, b: 2, c: 3}, ['a'], 'b');
    t.deepEqual(result, {a: 1, b: 2}, 'can restrict properties to those named in mixed args');
    result = pick(['a', 'b'], 1);
    t.deepEqual(result, {1: 'b'}, 'can pick numeric properties');

    t.deepEqual(pick(null, 'a', 'b'), {}, 'non objects return empty object');
    t.deepEqual(pick(undefined, 'toString'), {}, 'null/undefined return empty object');
    t.deepEqual(pick(5, 'toString', 'b'), {toString: Number.prototype.toString}, 'can iterate primitives');

    var data = {a: 1, b: 2, c: 3};
    var callback = function(value, key, object) {
        t.strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]);
        t.strictEqual(object, data);
        return value !== this.value;
    };
    result = pick(data, callback, {value: 2});
    t.deepEqual(result, {a: 1, c: 3}, 'can accept a predicate and context');

    var Obj = function(){};
    Obj.prototype = {a: 1, b: 2, c: 3};
    var instance = new Obj();
    t.deepEqual(pick(instance, 'a', 'c'), {a: 1, c: 3}, 'include prototype props');

    t.deepEqual(pick(data, function(val, key) {
        return this[key] === 3 && this === instance;
    }, instance), {c: 3}, 'function is given context');
    t.end();
});

Estimated bundle size increase

~555 B (details)

Dependencies

amp-property

amp-property

v1.0.2

Lodash Version: lodash.property

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns a function that will itself return the given propertyName of any passed-in object. Useful when iterating collections.

Example Usage

var property = require('amp-property');

var greetingGetter = property('greeting');
var person = {greeting: 'oh, hello!'};

greetingGetter(person); //=> 'oh, hello!'
module.exports = function property(key) {
    return function(obj) {
        return obj == null ? void 0 : obj[key];
    };
};
var test = require('tape');
var property = require('./property');


test('amp-property', function (t) {
    var greetingGetter = property('greeting');
    var person = {greeting: 'oh, hello!'};

    t.equal(greetingGetter(person), 'oh, hello!');
    t.doesNotThrow(function () {
        greetingGetter(null);
    }, 'should handle null-ish object issue #28');
    t.end();
});

Estimated bundle size increase

~27 B (details)

Dependencies

(none)

none

amp-values

amp-values

v1.0.1

Lodash Version: lodash.values

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns all the values of an object's properties as an array.

Example Usage

var values = require('amp-values');

var obj = {
    hi: 'there', 
    hello: 'you'
};
values(obj); //=> ['there', 'you']
var oKeys = require('amp-keys');


module.exports = function values(obj) {
    var keys = oKeys(obj);
    var length = keys.length;
    var vals = Array(length);
    for (var i = 0; i < length; i++) {
        vals[i] = obj[keys[i]];
    }
    return vals;
};
var test = require('tape');
var values = require('./values');


test('amp-values', function (t) {
    t.deepEqual(values({one: 1, two: 2}), [1, 2], 'can extract the values from an object');
    t.deepEqual(values({one: 1, two: 2, length: 3}), [1, 2, 3], 'works when one of them is "length"');
    t.end();
});

Estimated bundle size increase

~438 B (details)

Dependencies

amp-escape

amp-escape

v1.0.1

Lodash Version: lodash.escape

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Escapes (or unescapes) a string for insertion into HTML, by replacing &, <, >, ", ` , and ' characters with their corresponding HTML entities.

The vast majority of time you use this you just want to escape. But since 99% of the code is the same, there's also support for unescaping.

The main export is just the escape method, but we also attach escape and unescape as properties so you can use the style in second example if preferred.

Example Usage

var escape = require('amp-escape');

var htmlString = '<b>HI</b>';

var escaped = escape(htmlString); //=> '&lt;b&gt;HI&lt;/b&gt;'
escape.unescape(escaped); //=> '<b>HI</b>'

// Alternately, since both `escape` and `unescape`
// are attached to the main export you can also
// follow this style:
var escaper = require('amp-escape');

// then use them both as properties of `escaper`
escaper.escape(htmlString); //=> '&lt;b&gt;HI&lt;/b&gt;'
escaper.unescape(escaped); //=> '<b>HI</b>'
var keys = require('amp-keys');
var unescapeMap = {};
var escapeMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    '\'': '&#x27;',
    '`': '&#x60;'
};
for (var key in escapeMap) {
    unescapeMap[escapeMap[key]] = key;
}

 // Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
    var escaper = function(match) {
        return map[match];
    };
    // Regexes for identifying a key that needs to be escaped
    var source = '(?:' + keys(map).join('|') + ')';
    var testRegexp = RegExp(source);
    var replaceRegexp = RegExp(source, 'g');
    return function (string) {
        string = string == null ? '' : '' + string;
        return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
    };
};

var escape = createEscaper(escapeMap);

module.exports = escape;
module.exports.escape = escape;
module.exports.unescape = createEscaper(unescapeMap);
var test = require('tape');
var escape = require('./escape');
var unescape = escape.unescape;
var each = require('amp-each');


test('amp-escape', function (t) {
    t.equal(escape(null), '');

    var string = 'Curly & Moe';
    t.equal(unescape(null), '');
    t.equal(unescape(escape(string)), string);
    t.equal(unescape(string), string, 'don\'t unescape unnecessarily');

    // test & (&amp;) seperately obviously
    var escapeCharacters = ['<', '>', '"', '\'', '`'];

    each(escapeCharacters, function(escapeChar) {
      var str = 'a ' + escapeChar + ' string escaped';
      var escaped = escape(str);
      t.notEqual(str, escaped, escapeChar + ' is escaped');
      t.equal(str, unescape(escaped), escapeChar + ' can be unescaped');

      str = 'a ' + escapeChar + escapeChar + escapeChar + 'some more string' + escapeChar;
      escaped = escape(str);

      t.equal(escaped.indexOf(escapeChar), -1, 'can escape multiple occurances of ' + escapeChar);
      t.equal(unescape(escaped), str, 'multiple occurrences of ' + escapeChar + ' can be unescaped');
    });

    // handles multiple escape characters at once
    var joiner = ' other stuff ';
    var allEscaped = escapeCharacters.join(joiner);
    allEscaped += allEscaped;

    var error = false;
    each(escapeCharacters, function (escapeChar) {
        if (!error) {
            error = allEscaped.indexOf(escapeChar) === -1;
        }
    });
    t.ok(!error, 'handles multiple characters');
    t.ok(allEscaped.indexOf(joiner) >= 0, 'can escape multiple escape characters at the same time');

    // test & -> &amp;
    var str = 'some string & another string & yet another';
    var escaped = escape(str);

    t.ok(escaped.indexOf('&') !== -1, 'handles & aka &amp;');
    t.equal(unescape(str), str, 'can unescape &amp;');

    var start = '<b>Oh</b>, hello there!';
    var target = '&lt;b&gt;Oh&lt;/b&gt;, hello there!';
    
    t.equal(escape.escape(start), target, 'Should work using as `escape` property of export');
    t.equal(escape.unescape(target), start, 'Should work using as `unescape` property of export');

    t.end();
});

Estimated bundle size increase

~572 B (details)

Dependencies

amp-includes

amp-includes

v1.0.2

Lodash Version: lodash.includes

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if the first string contains the second string and false otherwise. You can also pass a startIndex as the third argument. If passed, the search will start at that index.

Example Usage

var includes = require('amp-includes');

var myString = 'Oh, hello there!';

includes(myString, 'hello'); //=> true
includes(myString, 'hello', 10); //=> false
includes(myString, 'hi'); //=> false

var indexOf = String.prototype.indexOf;


module.exports = function includes(string, query, position) {
    return indexOf.call(string, query, position) !== -1;
};
var test = require('tape');
var includes = require('./includes');


test('amp-includes', function (t) {
    var myString = 'Oh, hello there!';

    t.ok(includes(myString, 'hello'));
    t.notOk(includes(myString, 'hello', 10));
    t.ok(includes(myString, 'hello', 4));
    t.notOk(includes(myString, 'hello', 5));
    t.notOk(includes(myString, 'hi'));

    t.end();
});

Estimated bundle size increase

~37 B (details)

Dependencies

(none)

none

amp-to-camel-case

amp-to-camel-case

v1.0.1

Lodash Version: lodash.camelcase

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Camel cases a string by removing all whitespace and - and _ characters and capitalizing first letter following those. Takes a string like "hi world" and returns it as hiWorld. If you pass true as the second argument, it will also capitalize the first letter (sometimes referred to as Pascal case).

Note that multiple adjacent whitespace or - and _ characters are removed.

Example Usage

var toCamelCase = require('amp-to-camel-case');

toCamelCase('hi there'); //=> "hiThere"
toCamelCase('oh hello there', true); //=> "OhHelloThere"
var isString = require('amp-is-string');
var re1 = /([\W_\-]+\S?)/g;
var re2 = /[\W_]/g;


module.exports = function toCamelCase(string, capitalizeFirst) {
    if (!isString(string)) return '';
    var replaced = string.replace(re1, function (match) {
        return match.replace(re2, '').toUpperCase();
    });
    var first = replaced.slice(0, 1)[capitalizeFirst ? 'toUpperCase' : 'toLowerCase']();
    return first + replaced.slice(1);
};
var test = require('tape');
var toCamelCase = require('./to-camel-case');


test('amp-to-camel-case', function (t) {
    t.equal(toCamelCase(' hi world'), 'hiWorld');
    t.equal(toCamelCase('_hi_world'), 'hiWorld');
    t.equal(toCamelCase(' _ hi--world'), 'hiWorld');
    t.equal(toCamelCase(' _ hi2--world'), 'hi2World');
    t.equal(toCamelCase([]), '');
    t.equal(toCamelCase({}), '');
    t.equal(toCamelCase(1), '');
    t.equal(toCamelCase(' hi world', true), 'HiWorld');
    t.equal(toCamelCase('_hi_world', true), 'HiWorld');
    t.equal(toCamelCase(' _ hi--world', true), 'HiWorld');
    t.equal(toCamelCase(' _ hi2--world', true), 'Hi2World');
    t.end();
});

Estimated bundle size increase

~162 B (details)

Dependencies

amp-trim

amp-trim

v1.0.2

Lodash Version: lodash.trim

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Removes whitespace from both ends of the string.

Example Usage

var trim = require('amp-trim');

trim(' oh, hi there! '); //=> 'oh, hi there!'
// works for all whitespace types
trim('\n\r\t oh, hi there!'); //=> 'oh, hi there!'
var trimRE = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;


module.exports = function trim(string) {
    return string.replace(trimRE, '');
};
var test = require('tape');
var trim = require('./trim');


test('amp-trim', function (t) {
    t.equal(trim(' oh, hi there! '), 'oh, hi there!');
    t.equal(trim('   oh, hi there!'), 'oh, hi there!');
    t.equal(trim('\n\r\t oh, hi there!'), 'oh, hi there!', 'works for all whitespace types');
    t.end();
});

Estimated bundle size increase

~43 B (details)

Dependencies

(none)

none

amp-array-to-readable

amp-array-to-readable

v1.0.0

Docs

Takes an array of values and returns a readable string separated with comma and conjunction if length warrants it.

Example Usage

var arrayToReadable = require('amp-array-to-readable');

arrayToReadable([1, 2, 3]); //=> '1, 2, and 3'
arrayToReadable([1, 2]); //=> '1 and 2'
arrayToReadable([1]); //=> '1'

var words = ['one', 'two', 'three'];

arrayToReadable(words); //=> 'one, two, and three'
arrayToReadable(words, {conjunction: 'or'}); //=> 'one, two, or three'
arrayToReadable(words, {oxford: false}); //=> 'one, two and three'
module.exports = function arrayToReadable(arr, opts) {
    if (!opts) {
        opts = {};
    }
    var length = arr.length;
    var conj = opts.conjunction || 'and';
    var oxford = opts.oxford !== false;
    switch(length) {
        case 1:
            return arr[0].toString();
        case 2:
            return arr.join(' ' + conj + ' ');
        default:
            return arr.slice(0, -1).join(', ') + (oxford ? ',' : '') + ' ' + conj + ' ' + arr.slice(-1);
    }
};
var test = require('tape');
var arrayToReadable = require('./array-to-readable');


test('amp-array-to-readable', function (t) {
    t.equal(arrayToReadable([1, 2, 3]), '1, 2, and 3');
    t.equal(arrayToReadable([1, 2]), '1 and 2');
    t.equal(arrayToReadable([1]), '1');
    t.equal(arrayToReadable(['one', 'two', 'three', 'four']), 'one, two, three, and four');
    t.equal(arrayToReadable(['one', 'two', 'three', 'four'], {conjunction: 'or'}), 'one, two, three, or four');
    t.equal(arrayToReadable(['one', 'two', 'three', 'four'], {oxford: false}), 'one, two, three and four');
    t.end();
});

Estimated bundle size increase

~119 B (details)

Dependencies

(none)

none

amp-is-arguments

amp-is-arguments

v1.0.1

Lodash Version: lodash.isarguments

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is an arguments object and false for everything else.

Example Usage

var isArguments = require('amp-is-arguments');

isArguments(arguments); //=> true
isArguments([]); //=> false
var toString = Object.prototype.toString;
var hasOwn = Object.prototype.hasOwnProperty;
var isArgs = function isArgs(obj) {
    return toString.call(obj) === '[object Arguments]';
};

// for IE <9
if (!isArgs(arguments)) {
    isArgs = function (obj) {
        return obj && hasOwn.call(obj, 'callee');
    };
}

module.exports = isArgs;
var test = require('tape');
var isArguments = require('./is-arguments');


test('amp-is-arguments', function (t) {
    var args = (function(){ return arguments; }(1, 2, 3));
    t.ok(!isArguments('string'), 'a string is not an arguments object');
    t.ok(!isArguments(function () {}), 'a function is not an arguments object');
    t.ok(isArguments(args), 'but the arguments object is an arguments object');
    t.ok(!isArguments(Array.prototype.slice.call(args)), 'but not when it\'s converted into an array');
    t.ok(!isArguments([1, 2, 3]), 'and not vanilla arrays.');
    t.end();
});

Estimated bundle size increase

~89 B (details)

Dependencies

(none)

none

amp-is-array

amp-is-array

v1.0.1

Lodash Version: lodash.isarray

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is an Array and false for everything else. Uses native Array.isArray if available.

Example Usage

var isArray = require('amp-is-array');

isArray([]); //=> true
isArray([1, 2, 3]); //=> true
isArray(arguments); //=> false
var toString = Object.prototype.toString;
var nativeIsArray = Array.isArray;


module.exports = nativeIsArray || function isArray(obj) {
    return toString.call(obj) === '[object Array]';
};
var test = require('tape');
var isArray = require('./is-array');


test('amp-is-array', function (t) {
    t.ok(!isArray(undefined), 'undefined vars are not arrays');
    t.ok(!isArray(arguments), 'the arguments object is not an array');
    t.ok(isArray([1, 2, 3]), 'but arrays are');
    t.ok(isArray([]), 'even empty ones');
    t.end();
});

Estimated bundle size increase

~54 B (details)

Dependencies

(none)

none

amp-is-boolean

amp-is-boolean

v1.0.2

Lodash Version: lodash.isboolean

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is true or false. Returns false for everything else.

Example Usage

var isBoolean = require('amp-is-boolean');

isBoolean(true); //=> true
isBoolean(false); //=> true
isBoolean(0); //=> false
var toString = Object.prototype.toString;


module.exports = function isBoolean(obj) {
    return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
var test = require('tape');
var isBoolean = require('./is-boolean');


test('amp-is-boolean', function (t) {
    t.ok(!isBoolean(2), 'a number is not a boolean');
    t.ok(!isBoolean('string'), 'a string is not a boolean');
    t.ok(!isBoolean('false'), 'the string "false" is not a boolean');
    t.ok(!isBoolean('true'), 'the string "true" is not a boolean');
    t.ok(!isBoolean(arguments), 'the arguments object is not a boolean');
    t.ok(!isBoolean(undefined), 'undefined is not a boolean');
    t.ok(!isBoolean(NaN), 'NaN is not a boolean');
    t.ok(!isBoolean(null), 'null is not a boolean');
    t.ok(isBoolean(true), 'but true is');
    t.ok(isBoolean(false), 'and so is false');
    t.ok(isBoolean(new Boolean(false)), 'and so is class version of false');
    t.ok(isBoolean(new Boolean(true)), 'and so is class version of true');
    t.end();
});

Estimated bundle size increase

~55 B (details)

Dependencies

(none)

none

amp-is-date

amp-is-date

v1.0.1

Lodash Version: lodash.isdate

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is a Date and false for everything else.

Example Usage

var isDate = require('amp-is-date');

isDate(new Date()); //=> true
var toString = Object.prototype.toString;


module.exports = function isFunction(obj) {
    return toString.call(obj) === '[object Date]';
};
var test = require('tape');
var isDate = require('./is-date');


test('amp-is-date', function (t) {
    t.ok(!isDate(100), 'numbers are not dates');
    t.ok(!isDate({}), 'objects are not dates');
    t.ok(isDate(new Date()), 'but dates are');
    t.end();
});

Estimated bundle size increase

~42 B (details)

Dependencies

(none)

none

amp-is-empty

amp-is-empty

v1.0.2

Lodash Version: lodash.isempty

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed an "empty" value and false for everything else.

Empty is defined as:

  • empty objects: {}
  • empty arrays: []
  • empty string: ''
  • undefined
  • null
  • NaN
  • the number zero: 0

Example Usage

var isEmpty = require('amp-is-empty');

isEmpty({}); //=> true
isEmpty([]); //=> true
isEmpty(''); //=> true
isEmpty(0); //=> true
isEmpty(null); //=> true
isEmpty(undefined); //=> true
isEmpty(NaN); //=> true
var isArray = require('amp-is-array');
var isString = require('amp-is-string');
var isArguments = require('amp-is-arguments');
var isNumber = require('amp-is-number');
var isNan = require('amp-is-nan');
var keys = require('amp-keys');


module.exports = function isEmpty(obj) {
    if (obj == null) return true;
    if (isArray(obj) || isString(obj) || isArguments(obj)) return obj.length === 0;
    if (isNumber(obj)) return obj === 0 || isNan(obj);
    if (keys(obj).length !== 0) return false;
    return true;
};
var test = require('tape');
var isEmpty = require('./is-empty');


test('amp-is-empty', function (t) {
    t.ok(!isEmpty([1]), '[1] is not empty');
    t.ok(isEmpty([]), '[] is empty');
    t.ok(!isEmpty({one : 1}), '{one : 1} is not empty');
    t.ok(isEmpty({}), '{} is empty');
    t.ok(isEmpty(new RegExp('')), 'objects with prototype properties are empty');
    t.ok(isEmpty(null), 'null is empty');
    t.ok(isEmpty(NaN), 'NaN is empty');
    t.ok(isEmpty(), 'undefined is empty');
    t.ok(isEmpty(''), 'the empty string is empty');
    t.ok(isEmpty(0), 'the number zero is empty');
    t.ok(!isEmpty(1), 'other numbers are not empty');
    t.ok(!isEmpty('moe'), 'but other strings are not');

    var obj = {one : 1};
    delete obj.one;
    t.ok(isEmpty(obj), 'deleting all the keys from an object empties it');

    var args = function(){ return arguments; };
    t.ok(isEmpty(args()), 'empty arguments object is empty');
    t.ok(!isEmpty(args('')), 'non-empty arguments object is not empty');
    t.end();
});

Estimated bundle size increase

~601 B (details)

Dependencies

amp-is-function

amp-is-function

v1.0.1

Lodash Version: lodash.isfunction

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is a Function and false for everything else.

Example Usage

var isFunction = require('amp-is-function');

isFunction(function () {}); //=> true
isFunction({}); //=> false
var toString = Object.prototype.toString;
var func = function isFunction(obj) {
    return toString.call(obj) === '[object Function]';
};

// Optimize `isFunction` if appropriate. Work around an IE 11 bug.
if (typeof /./ !== 'function') {
    func = function isFunction(obj) {
      return typeof obj == 'function' || false;
    };
}

module.exports = func;
var test = require('tape');
var isFunction = require('./is-function');


test('amp-is-function', function (t) {
    t.ok(!isFunction(undefined), 'undefined vars are not functions');
    t.ok(!isFunction([1, 2, 3]), 'arrays are not functions');
    t.ok(!isFunction('moe'), 'strings are not functions');
    if (typeof document !== 'undefined') {
        t.ok(!isFunction(document.createElement('div')), 'elements are not functions');
    }
    t.ok(isFunction(isFunction), 'but functions are');
    t.ok(isFunction(function(){}), 'even anonymous ones');
    t.end();
});

Estimated bundle size increase

~65 B (details)

Dependencies

(none)

none

amp-is-nan

amp-is-nan

v1.0.1

Lodash Version: lodash.isnan

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Tests whether object passed in is a NaN. Native implementations of isNaN return true when passed undefined. So if you want to test whether NaN is exactly NaN this does that.

Example Usage

var isNan = require('amp-is-nan');

isNan(NaN); //=> true
isNan(undefined); //=> false
isNan(0); //=> false
var isNumber = require('amp-is-number');


module.exports = function isNaN(obj) {
    return isNumber(obj) && obj !== +obj;
};
var test = require('tape');
var isNan = require('./is-nan');


test('amp-is-nan', function (t) {
    t.ok(!isNan(undefined), 'undefined is not NaN');
    t.ok(!isNan(null), 'null is not NaN');
    t.ok(!isNan(0), '0 is not NaN');
    t.ok(isNan(NaN), 'but NaN is');
    t.ok(isNan(new Number(NaN)), 'wrapped NaN is still NaN');
    t.end();
});

Estimated bundle size increase

~77 B (details)

Dependencies

amp-is-null

amp-is-null

v1.0.1

Lodash Version: lodash.isnull

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is null and false for everything else.

Example Usage

var isNull = require('amp-is-null');

isNull(null); //=> true
isNull('anything else'); //=> false
module.exports = function isNull(obj) {
    return obj === null;
};
var test = require('tape');
var isNull = require('./is-null');


test('amp-is-null', function (t) {
    t.ok(!isNull(undefined), 'undefined is not null');
    t.ok(!isNull(NaN), 'NaN is not null');
    t.ok(isNull(null), 'but null is');
    t.end();
});

Estimated bundle size increase

~14 B (details)

Dependencies

(none)

none

amp-is-number

amp-is-number

v1.0.1

Lodash Version: lodash.isnumber

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is a number and false for everything else.

Example Usage

var isNumber = require('amp-is-number');

isNumber(5); //=> true
isNumber(Infinity); //=> true
isNumber('5'); //=> false
var toString = Object.prototype.toString;


module.exports = function isNumber(obj) {
    return toString.call(obj) === '[object Number]';
};
var test = require('tape');
var isNumber = require('./is-number');


test('amp-is-number', function (t) {
    t.ok(!isNumber('string'), 'a string is not a number');
    t.ok(!isNumber(arguments), 'the arguments object is not a number');
    t.ok(!isNumber(undefined), 'undefined is not a number');
    t.ok(isNumber(3 * 4 - 7 / 10), 'but numbers are');
    t.ok(isNumber(NaN), 'NaN *is* a number');
    t.ok(isNumber(new Number(5)), 'number objects are numbers');
    t.ok(isNumber(Infinity), 'Infinity is a number');
    t.ok(!isNumber('1'), 'numeric strings are not numbers');
    t.end();
});

Estimated bundle size increase

~44 B (details)

Dependencies

(none)

none

amp-is-object

amp-is-object

v1.0.1

Lodash Version: lodash.isobject

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is an Object. Arrays and functions are objects too, while (normal) strings and numbers are not.

So this is not a strict check per JS where typeof null returns 'object'. This is a more practical runtime check that is useful for trying to find out whether you got passed an options object or a simple argument to a function.

Example Usage

var isObject = require('amp-is-object');

isObject({}); //=> true
isObject(null); //=> false
isObject('oh, hello there'); //=> false
isObject(['hi', 'there']); //=> true
// this is not something you'd normally do, but...
isObject(new String('hi')); //=> true

module.exports = function isObject(obj) {
    var type = typeof obj;
    return !!obj && (type === 'function' || type === 'object');
};
/*global document*/
var test = require('tape');
var isObject = require('./is-object');


test('amp-is-object', function(t) {
    t.ok(isObject(arguments), 'the arguments object is object');
    t.ok(isObject([1, 2, 3]), 'and arrays');
    if (typeof document !== 'undefined') {
        t.ok(isObject(document.body), 'and DOM element');
    }
    t.ok(isObject(function () {}), 'and functions');
    t.ok(!isObject(null), 'but not null');
    t.ok(!isObject(undefined), 'and not undefined');
    t.ok(!isObject('string'), 'and not string');
    t.ok(!isObject(12), 'and not number');
    t.ok(!isObject(true), 'and not boolean');
    t.ok(isObject(new String('string')), 'but new String()');
    t.end();
});

Estimated bundle size increase

~29 B (details)

Dependencies

(none)

none

amp-is-object-equal

amp-is-object-equal

v1.0.2

Lodash Version: lodash.isequal

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

Example Usage

var isObjectEqual = require('amp-is-object-equal');

var swede = {name: 'Swede', greeting: ['oh', 'hello', 'there']};
var swedeClone = {name: 'Swede', greeting: ['oh', 'hello', 'there']};

// they're not the same instance
swede == swedeClone; //=> false 
// but they're deep equal
isObjectEqual(swede1, swedeClone); //=> true
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
var objKeys = require('amp-keys');
var isFunction = require('amp-is-function');


// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
    if (a === b) return a !== 0 || 1 / a === 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className !== toString.call(b)) return false;
    switch (className) {
        // Strings, numbers, regular expressions, dates, and booleans are compared by value.
        case '[object RegExp]':
        // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
        case '[object String]':
            // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
            // equivalent to `new String("5")`.
            return '' + a === '' + b;
        case '[object Number]':
            // `NaN`s are equivalent, but non-reflexive.
            // Object(NaN) is equivalent to NaN
            if (+a !== +a) return +b !== +b;
            // An `egal` comparison is performed for other numeric values.
            return +a === 0 ? 1 / +a === 1 / b : +a === +b;
        case '[object Date]':
        case '[object Boolean]':
            // Coerce dates and booleans to numeric primitive values. Dates are compared by their
            // millisecond representations. Note that invalid dates with millisecond representations
            // of `NaN` are not equivalent.
            return +a === +b;
    }

    var areArrays = className === '[object Array]';
    if (!areArrays) {
        if (typeof a != 'object' || typeof b != 'object') return false;

        // Objects with different constructors are not equivalent, but `Object`s or `Array`s
        // from different frames are.
        var aCtor = a.constructor, bCtor = b.constructor;
        if (aCtor !== bCtor && 
            !(isFunction(aCtor) && 
            aCtor instanceof aCtor &&
            isFunction(bCtor) && 
            bCtor instanceof bCtor) && 
            ('constructor' in a && 'constructor' in b)) {
            return false;
        }
    }
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
    var length = aStack.length;
    while (length--) {
        // Linear search. Performance is inversely proportional to the number of
        // unique nested structures.
        if (aStack[length] === a) return bStack[length] === b;
    }

    // Add the first object to the stack of traversed objects.
    aStack.push(a);
    bStack.push(b);
    var size, result;
    // Recursively compare objects and arrays.
    if (areArrays) {
        // Compare array lengths to determine if a deep comparison is necessary.
        size = a.length;
        result = size === b.length;
        if (result) {
            // Deep compare the contents, ignoring non-numeric properties.
            while (size--) {
                if (!(result = eq(a[size], b[size], aStack, bStack))) break;
            }
        }
    } else {
        // Deep compare objects.
        var keys = objKeys(a), key;
        size = keys.length;
        // Ensure that both objects contain the same number of properties before comparing deep equality.
        result = objKeys(b).length === size;
        if (result) {
            while (size--) {
                // Deep compare each member
                key = keys[size];
                if (!(result = hasOwn.call(b, key) && eq(a[key], b[key], aStack, bStack))) break;
            }
        }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop();
    bStack.pop();
    return result;
};


module.exports = function isEqual(a, b) {
    return eq(a, b, [], []);
};
/*global String*/
var test = require('tape');
var isObjectEqual = require('./is-object-equal');


test('amp-is-object-equal', function (t) {
    function First() {
      this.value = 1;
    }
    First.prototype.value = 1;
    function Second() {
      this.value = 1;
    }
    Second.prototype.value = 2;

    // Basic equality and identity comparisons.
    t.ok(isObjectEqual(null, null), '`null` is equal to `null`');
    t.ok(isObjectEqual(), '`undefined` is equal to `undefined`');

    t.ok(!isObjectEqual(0, -0), '`0` is not equal to `-0`');
    t.ok(!isObjectEqual(-0, 0), 'Commutative equality is implemented for `0` and `-0`');
    t.ok(!isObjectEqual(null, undefined), '`null` is not equal to `undefined`');
    t.ok(!isObjectEqual(undefined, null), 'Commutative equality is implemented for `null` and `undefined`');

    // String object and primitive comparisons.
    t.ok(isObjectEqual('Curly', 'Curly'), 'Identical string primitives are equal');
    t.ok(isObjectEqual(new String('Curly'), new String('Curly')), 'String objects with identical primitive values are equal');
    t.ok(isObjectEqual(new String('Curly'), 'Curly'), 'String primitives and their corresponding object wrappers are equal');
    t.ok(isObjectEqual('Curly', new String('Curly')), 'Commutative equality is implemented for string objects and primitives');

    t.ok(!isObjectEqual('Curly', 'Larry'), 'String primitives with different values are not equal');
    t.ok(!isObjectEqual(new String('Curly'), new String('Larry')), 'String objects with different primitive values are not equal');
    t.ok(!isObjectEqual(new String('Curly'), {toString: function(){ return 'Curly'; }}), 'String objects and objects with a custom `toString` method are not equal');

    // Number object and primitive comparisons.
    t.ok(isObjectEqual(75, 75), 'Identical number primitives are equal');
    t.ok(isObjectEqual(new Number(75), new Number(75)), 'Number objects with identical primitive values are equal');
    t.ok(isObjectEqual(75, new Number(75)), 'Number primitives and their corresponding object wrappers are equal');
    t.ok(isObjectEqual(new Number(75), 75), 'Commutative equality is implemented for number objects and primitives');
    t.ok(!isObjectEqual(new Number(0), -0), '`new Number(0)` and `-0` are not equal');
    t.ok(!isObjectEqual(0, new Number(-0)), 'Commutative equality is implemented for `new Number(0)` and `-0`');

    t.ok(!isObjectEqual(new Number(75), new Number(63)), 'Number objects with different primitive values are not equal');
    t.ok(!isObjectEqual(new Number(63), {valueOf: function(){ return 63; }}), 'Number objects and objects with a `valueOf` method are not equal');

    // Comparisons involving `NaN`.
    t.ok(isObjectEqual(NaN, NaN), '`NaN` is equal to `NaN`');
    t.ok(isObjectEqual(new Object(NaN), NaN), 'Object(`NaN`) is equal to `NaN`');
    t.ok(!isObjectEqual(61, NaN), 'A number primitive is not equal to `NaN`');
    t.ok(!isObjectEqual(new Number(79), NaN), 'A number object is not equal to `NaN`');
    t.ok(!isObjectEqual(Infinity, NaN), '`Infinity` is not equal to `NaN`');

    // Boolean object and primitive comparisons.
    t.ok(isObjectEqual(true, true), 'Identical boolean primitives are equal');
    t.ok(isObjectEqual(new Boolean, new Boolean), 'Boolean objects with identical primitive values are equal');
    t.ok(isObjectEqual(true, new Boolean(true)), 'Boolean primitives and their corresponding object wrappers are equal');
    t.ok(isObjectEqual(new Boolean(true), true), 'Commutative equality is implemented for booleans');
    t.ok(!isObjectEqual(new Boolean(true), new Boolean), 'Boolean objects with different primitive values are not equal');

    // Common type coercions.
    t.ok(!isObjectEqual(new Boolean(false), true), '`new Boolean(false)` is not equal to `true`');
    t.ok(!isObjectEqual('75', 75), 'String and number primitives with like values are not equal');
    t.ok(!isObjectEqual(new Number(63), new String(63)), 'String and number objects with like values are not equal');
    t.ok(!isObjectEqual(75, '75'), 'Commutative equality is implemented for like string and number values');
    t.ok(!isObjectEqual(0, ''), 'Number and string primitives with like values are not equal');
    t.ok(!isObjectEqual(1, true), 'Number and boolean primitives with like values are not equal');
    t.ok(!isObjectEqual(new Boolean(false), new Number(0)), 'Boolean and number objects with like values are not equal');
    t.ok(!isObjectEqual(false, new String('')), 'Boolean primitives and string objects with like values are not equal');
    t.ok(!isObjectEqual(12564504e5, new Date(2009, 9, 25)), 'Dates and their corresponding numeric primitive values are not equal');

    // Dates.
    t.ok(isObjectEqual(new Date(2009, 9, 25), new Date(2009, 9, 25)), 'Date objects referencing identical times are equal');
    t.ok(!isObjectEqual(new Date(2009, 9, 25), new Date(2009, 11, 13)), 'Date objects referencing different times are not equal');
    t.ok(!isObjectEqual(new Date(2009, 11, 13), {
      getTime: function(){
        return 12606876e5;
      }
    }), 'Date objects and objects with a `getTime` method are not equal');
    t.ok(!isObjectEqual(new Date('Curly'), new Date('Curly')), 'Invalid dates are not equal');

    // Functions.
    t.ok(!isObjectEqual(First, Second), 'Different functions with identical bodies and source code representations are not equal');

    // RegExps.
    t.ok(isObjectEqual(/(?:)/gim, /(?:)/gim), 'RegExps with equivalent patterns and flags are equal');
    t.ok(isObjectEqual(/(?:)/gi, /(?:)/ig), 'Flag order is not significant');
    t.ok(!isObjectEqual(/(?:)/g, /(?:)/gi), 'RegExps with equivalent patterns and different flags are not equal');
    t.ok(!isObjectEqual(/Moe/gim, /Curly/gim), 'RegExps with different patterns and equivalent flags are not equal');
    t.ok(!isObjectEqual(/(?:)/gi, /(?:)/g), 'Commutative equality is implemented for RegExps');
    t.ok(!isObjectEqual(/Curly/g, {source: 'Larry', global: true, ignoreCase: false, multiline: false}), 'RegExps and RegExp-like objects are not equal');

    // Empty arrays, array-like objects, and object literals.
    t.ok(isObjectEqual({}, {}), 'Empty object literals are equal');
    t.ok(isObjectEqual([], []), 'Empty array literals are equal');
    t.ok(isObjectEqual([{}], [{}]), 'Empty nested arrays and objects are equal');
    t.ok(!isObjectEqual({length: 0}, []), 'Array-like objects and arrays are not equal.');
    t.ok(!isObjectEqual([], {length: 0}), 'Commutative equality is implemented for array-like objects');

    t.ok(!isObjectEqual({}, []), 'Object literals and array literals are not equal');
    t.ok(!isObjectEqual([], {}), 'Commutative equality is implemented for objects and arrays');

    // Arrays with primitive and object values.
    t.ok(isObjectEqual([1, 'Larry', true], [1, 'Larry', true]), 'Arrays containing identical primitives are equal');
    t.ok(isObjectEqual([/Moe/g, new Date(2009, 9, 25)], [/Moe/g, new Date(2009, 9, 25)]), 'Arrays containing equivalent elements are equal');

    // Multi-dimensional arrays.
    var a = [new Number(47), false, 'Larry', /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}];
    var b = [new Number(47), false, 'Larry', /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}];
    t.ok(isObjectEqual(a, b), 'Arrays containing nested arrays and objects are recursively compared');

    // Overwrite the methods defined in ES 5.1 section 15.4.4.
    a.forEach = a.map = a.filter = a.every = a.indexOf = a.lastIndexOf = a.some = a.reduce = a.reduceRight = null;
    b.join = b.pop = b.reverse = b.shift = b.slice = b.splice = b.concat = b.sort = b.unshift = null;

    // Array elements and properties.
    t.ok(isObjectEqual(a, b), 'Arrays containing equivalent elements and different non-numeric properties are equal');
    a.push('White Rocks');
    t.ok(!isObjectEqual(a, b), 'Arrays of different lengths are not equal');
    a.push('East Boulder');
    b.push('Gunbarrel Ranch', 'Teller Farm');
    t.ok(!isObjectEqual(a, b), 'Arrays of identical lengths containing different elements are not equal');

    // Sparse arrays.
    t.ok(isObjectEqual(Array(3), Array(3)), 'Sparse arrays of identical lengths are equal');
    t.ok(!isObjectEqual(Array(3), Array(6)), 'Sparse arrays of different lengths are not equal when both are empty');

    var sparse = [];
    sparse[1] = 5;
    t.ok(isObjectEqual(sparse, [undefined, 5]), 'Handles sparse arrays as dense');

    // Simple objects.
    t.ok(isObjectEqual({a: 'Curly', b: 1, c: true}, {a: 'Curly', b: 1, c: true}), 'Objects containing identical primitives are equal');
    t.ok(isObjectEqual({a: /Curly/g, b: new Date(2009, 11, 13)}, {a: /Curly/g, b: new Date(2009, 11, 13)}), 'Objects containing equivalent members are equal');
    t.ok(!isObjectEqual({a: 63, b: 75}, {a: 61, b: 55}), 'Objects of identical sizes with different values are not equal');
    t.ok(!isObjectEqual({a: 63, b: 75}, {a: 61, c: 55}), 'Objects of identical sizes with different property names are not equal');
    t.ok(!isObjectEqual({a: 1, b: 2}, {a: 1}), 'Objects of different sizes are not equal');
    t.ok(!isObjectEqual({a: 1}, {a: 1, b: 2}), 'Commutative equality is implemented for objects');
    t.ok(!isObjectEqual({x: 1, y: undefined}, {x: 1, z: 2}), 'Objects with identical keys and different values are not equivalent');

    // `A` contains nested objects and arrays.
    a = {
      name: new String('Moe Howard'),
      age: new Number(77),
      stooge: true,
      hobbies: ['acting'],
      film: {
        name: 'Sing a Song of Six Pants',
        release: new Date(1947, 9, 30),
        stars: [new String('Larry Fine'), 'Shemp Howard'],
        minutes: new Number(16),
        seconds: 54
      }
    };

    // `B` contains equivalent nested objects and arrays.
    b = {
      name: new String('Moe Howard'),
      age: new Number(77),
      stooge: true,
      hobbies: ['acting'],
      film: {
        name: 'Sing a Song of Six Pants',
        release: new Date(1947, 9, 30),
        stars: [new String('Larry Fine'), 'Shemp Howard'],
        minutes: new Number(16),
        seconds: 54
      }
    };
    t.ok(isObjectEqual(a, b), 'Objects with nested equivalent members are recursively compared');

    // Instances.
    t.ok(isObjectEqual(new First, new First), 'Object instances are equal');
    t.ok(!isObjectEqual(new First, new Second), 'Objects with different constructors and identical own properties are not equal');
    t.ok(!isObjectEqual({value: 1}, new First), 'Object instances and objects sharing equivalent properties are not equal');
    t.ok(!isObjectEqual({value: 2}, new Second), 'The prototype chain of objects should not be examined');

    // Circular Arrays.
    (a = []).push(a);
    (b = []).push(b);
    t.ok(isObjectEqual(a, b), 'Arrays containing circular references are equal');
    a.push(new String('Larry'));
    b.push(new String('Larry'));
    t.ok(isObjectEqual(a, b), 'Arrays containing circular references and equivalent properties are equal');
    a.push('Shemp');
    b.push('Curly');
    t.ok(!isObjectEqual(a, b), 'Arrays containing circular references and different properties are not equal');

    // More circular arrays #767.
    a = ['everything is checked but', 'this', 'is not'];
    a[1] = a;
    b = ['everything is checked but', ['this', 'array'], 'is not'];
    t.ok(!isObjectEqual(a, b), 'Comparison of circular references with non-circular references are not equal');

    // Circular Objects.
    a = {abc: null};
    b = {abc: null};
    a.abc = a;
    b.abc = b;
    t.ok(isObjectEqual(a, b), 'Objects containing circular references are equal');
    a.def = 75;
    b.def = 75;
    t.ok(isObjectEqual(a, b), 'Objects containing circular references and equivalent properties are equal');
    a.def = new Number(75);
    b.def = new Number(63);
    t.ok(!isObjectEqual(a, b), 'Objects containing circular references and different properties are not equal');

    // More circular objects #767.
    a = {everything: 'is checked', but: 'this', is: 'not'};
    a.but = a;
    b = {everything: 'is checked', but: {that: 'object'}, is: 'not'};
    t.ok(!isObjectEqual(a, b), 'Comparison of circular references with non-circular object references are not equal');

    // Cyclic Structures.
    a = [{abc: null}];
    b = [{abc: null}];
    (a[0].abc = a).push(a);
    (b[0].abc = b).push(b);
    t.ok(isObjectEqual(a, b), 'Cyclic structures are equal');
    a[0].def = 'Larry';
    b[0].def = 'Larry';
    t.ok(isObjectEqual(a, b), 'Cyclic structures containing equivalent properties are equal');
    a[0].def = new String('Larry');
    b[0].def = new String('Curly');
    t.ok(!isObjectEqual(a, b), 'Cyclic structures containing different properties are not equal');

    // Complex Circular References.
    a = {foo: {b: {foo: {c: {foo: null}}}}};
    b = {foo: {b: {foo: {c: {foo: null}}}}};
    a.foo.b.foo.c.foo = a;
    b.foo.b.foo.c.foo = b;
    t.ok(isObjectEqual(a, b), 'Cyclic structures with nested and identically-named properties are equal');

    // Objects without a `constructor` property
    if (Object.create) {
        a = Object.create(null, {x: {value: 1, enumerable: true}});
        b = {x: 1};
        t.ok(isObjectEqual(a, b), 'Handles objects without a constructor (e.g. from Object.create');
    }

    function Foo() { this.a = 1; }
    Foo.prototype.constructor = null;

    var other = {a: 1};
    t.strictEqual(isObjectEqual(new Foo, other), false, 'Objects from different constructors are not equal');
    t.end();
});

Estimated bundle size increase

~810 B (details)

Dependencies

amp-is-regexp

amp-is-regexp

v1.0.1

Lodash Version: lodash.isregexp

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is a a regular expression and false for everything else.

Example Usage

var isRegexp = require('amp-is-regexp');

isRegexp(/oh hello there/); //=> true
isRegexp(new RegExp('oh hello there')); //=> true
var toString = Object.prototype.toString;


module.exports = function isRegExp(obj) {
    return toString.call(obj) === '[object RegExp]';
};
var test = require('tape');
var isRegExp = require('./is-regexp');


test('amp-is-regexp', function (t) {
    t.ok(!isRegExp(function () {}), 'functions are not RegExps');
    t.ok(isRegExp(/identity/), 'but RegExps are');
    t.end();
});

Estimated bundle size increase

~45 B (details)

Dependencies

(none)

none

amp-is-string

amp-is-string

v1.0.1

Lodash Version: lodash.isstring

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is a string (including empty string) and false for everything else.

Example Usage

var isString = require('amp-is-string');

isString('oh, hello there!'); //=> true
isString(''); //=> true
isString(5); //=> false
var toString = Object.prototype.toString;


module.exports = function isString(obj) {
    return toString.call(obj) === '[object String]';
};
var test = require('tape');
var isString = require('./is-string');


test('amp-is-string', function (t) {
    t.ok(!isString({}), 'an object is not a string');
    t.ok(isString([1, 2, 3].join(', ')), 'but strings are');
    t.ok(isString('I am a string literal'), 'string literals are');
    var obj = new String('I am a string object');
    t.ok(isString(obj), 'so are String objects');
    t.ok(isString(''), 'empty string is still a string');
    t.end();
});

Estimated bundle size increase

~41 B (details)

Dependencies

(none)

none

amp-is-undefined

amp-is-undefined

v1.0.1

Lodash Version: lodash.isundefined

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns true if passed value is undefined and false for everything else (including other falsy values, null, and NaN).

Example Usage

var isUndefined = require('amp-is-undefined');

isUndefined(null); //=> false
isUndefined(NaN); //=> false
isUndefined(undefined); //=> true

module.exports = function isUndefined(obj) {
    return obj === void 0;
};
var test = require('tape');
var isUndefined = require('./is-undefined');


test('amp-is-undefined', function (t) {
    t.ok(!isUndefined(1), 'numbers are defined');
    t.ok(!isUndefined(null), 'null is defined');
    t.ok(!isUndefined(false), 'false is defined');
    t.ok(!isUndefined(NaN), 'NaN is defined');
    t.ok(isUndefined(), 'nothing is undefined');
    t.ok(isUndefined(undefined), 'undefined is undefined');
    t.end();
});

Estimated bundle size increase

~15 B (details)

Dependencies

(none)

none

amp-iteratee

amp-iteratee

v1.0.1

Lodash Version: lodash.callback

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

An internal function to generate callbacks that can be applied to each element in a collection, returning the desired result — either identity, an arbitrary callback, a property matcher, or a property accessor.

Used in many of the collection and array functions.

Example Usage

var iteratee = require('amp-iteratee');


var someUtil = function (array, fn, context) {
    var iteratee = createIteratee(fn, context, 3);
    var result = [];

    for (var i = 0, l = array.length; i < l; i++) {
        result[i] = iteratee(array[i], i, array);
    } 
    return result;
};
var isFunction = require('amp-is-function');
var isObject = require('amp-is-object');
var createCallback = require('amp-create-callback');
var matches = require('amp-matches');
var property = require('amp-property');
var identity = function (val) { return val; };


module.exports = function iteratee(value, context, argCount) {
    if (value == null) return identity;
    if (isFunction(value)) return createCallback(value, context, argCount);
    if (isObject(value)) return matches(value);
    return property(value);
};
var test = require('tape');
var iteratee = require('./iteratee');
var createCallback = require('amp-create-callback');
var matches = require('amp-matches');
var property = require('amp-property');


test('amp-iteratee', function (t) {
    t.equal(iteratee()('hi'), 'hi', 'calling with empty values should return an identity function');
    t.equal(iteratee(null)('hi'), 'hi', 'calling with null should return an identity function');
    
    var context = {};
    var actualContext;
    var func = function () {
        actualContext = this;
        return 'hi';
    };
    
    t.equal(iteratee(func).toString(), createCallback(func).toString(), 'fn should return same as createCallback');
    t.equal(iteratee(func, context)(), 'hi', 'fn should return same as createCallback');
    t.equal(context, actualContext, 'should have retained passed context');
    
    // passing an object
    var matcher = {awesome: true};
    var func1 = iteratee(matcher);
    var func2 = matches(matcher);

    var personToCheck = {name: 'someone', awesome: true};

    t.strictEqual(func1(personToCheck), true, 'should create a matcher that returns true');
    t.equal(func1(personToCheck), func2(personToCheck), 'when given a function, creates callback that works same as createCallback');
    
    // passing a property name
    var propertyName = 'name';

    func1 = iteratee(propertyName);
    func2 = property(propertyName);

    var personToCheck = {name: 'someone', awesome: true};

    t.equal(func1(personToCheck), 'someone', 'works like property when passed a string');
    t.equal(func1(personToCheck), func2(personToCheck), 'gives sames result as property');

    t.end();
});

Estimated bundle size increase

~774 B (details)

Dependencies

amp-random

amp-random

v1.0.0

Lodash Version: lodash.random

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Return a random integer between min and max (inclusive).

If only one number is passed, it is assumed to be the max and min will be 0.

Example Usage

var random = require('amp-random');

// call with min and max
random(3, 100); //=> 42 (sometimes)

// call with just a max
random(10); //=> 3 (return a number between `0` and `10`)
module.exports = function random(min, max) {
    if (max == null) {
        max = min;
        min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
};
var test = require('tape');
var random = require('./random');
var every = require('amp-every');
var some = require('amp-some');
var range = require('amp-range');


test('amp-random', function (t) {
    var array = range(1000);
    var min = Math.pow(2, 31);
    var max = Math.pow(2, 62);

    t.ok(every(array, function() {
      return random(min, max) >= min;
    }), 'should produce a random number greater than or equal to the minimum number');

    t.ok(some(array, function() {
      return random(Number.MAX_VALUE) > 0;
    }), 'should produce a random number when passed `Number.MAX_VALUE`');
    t.end();
});

Estimated bundle size increase

~43 B (details)

Dependencies

(none)

none

amp-result

amp-result

v1.1.0

Lodash Version: lodash.result

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Returns the value of the named property, or if it's a function invoke it with the object as context. If no such property exists, returns undefined or the defaultValue. If defaultValue is a function it will be executed and its result returned.

Example Usage

var result = require('amp-result');
var obj = {
    hi: 'there',
    oh: function () {
        return 'hello there'
    }
};

result(obj, 'hi'); //=> 'there'
result(obj, 'oh'); //=> 'hello there'
result(obj, 'nothing', 'wat'); //=> 'wat'
var isFunction = require('amp-is-function');


module.exports = function result(object, property, defaultValue) {
    var value = object == null ? void 0 : object[property];
    if (value === void 0) {
        return isFunction(defaultValue) ? defaultValue() : defaultValue;
    }
    return isFunction(value) ? object[property]() : value;
};
var test = require('tape');
var result = require('./result');


test('amp-result', function(t) {
    var obj = {
        w: '',
        x: 'x',
        y: function () {
            return this.x;
        }
    };
    t.strictEqual(result(obj, 'w'), '');
    t.strictEqual(result(obj, 'x'), 'x');
    t.strictEqual(result(obj, 'y'), 'x');
    t.strictEqual(result(obj, 'z'), undefined);
    t.strictEqual(result(null, 'x'), undefined);

    t.strictEqual(result(null, 'b', 'default'), 'default');
    t.strictEqual(result(undefined, 'c', 'default'), 'default');
    t.strictEqual(result(''.match('missing'), 1, 'default'), 'default');

    t.strictEqual(result({d: null}, 'd', 'default'), null);
    t.strictEqual(result({e: false}, 'e', 'default'), false);

    t.strictEqual(result({}, 'b', 'default'), 'default');
    t.strictEqual(result({d: undefined}, 'd', 'default'), 'default');

    var Foo = function(){};
    Foo.prototype.bar = 1;
    t.strictEqual(result(new Foo, 'bar', 2), 1);

    var obj = {a: function() {}};
    t.strictEqual(result(obj, 'a', 'failed'), undefined);

    var defaultFunc = function () {
        return 'hi';
    };

    t.strictEqual(result({}, 'something', defaultFunc), 'hi', 'should execute default value if func');

    t.end();
});

Estimated bundle size increase

~137 B (details)

Dependencies

amp-unique-id

amp-unique-id

v1.0.2

Lodash Version: lodash.uniqueid

The lodash project now has an independently versioned module that serves the same purpose as this. We recommend you use it for new projects. See this post for more details.

Docs

Generates a simple integer-based unique ID string. This is not a uuid, it's for simpler things like ids for DOM elements or client instances. Its uniqueness is only guaranteed by the fact that it's a single, global, always incremented counter. If a prefix is passed, the id will be appended to it.

In order to ensure uniqueness in the case where two instances of this module is required, we keep the counter variable attached to window or global (in the case of node).

Example Usage

var uniqueId = require('amp-unique-id');

uniqueId(); //=> "1"
uniqueId('hi_'); //=> "hi_2"
/*global window, global*/
var theGlobal = (typeof window !== 'undefined') ? window : global;
if (!theGlobal.__ampIdCounter) {
    theGlobal.__ampIdCounter = 0;
}


module.exports = function uniqueId(prefix) {
    var id = ++theGlobal.__ampIdCounter + '';
    return prefix ? prefix + id : id;
};
var test = require('tape');
var uniqueId = require('./unique-id');


test('amp-unique-id', function (t) {
    var ids = [], i = 0;
    while (i++ < 5) ids.push(uniqueId());
    i = 0;
    while (i++ < 5) ids.push(uniqueId('p'));
    t.deepEqual(ids, ['1', '2', '3', '4', '5', 'p6', 'p7', 'p8', 'p9', 'p10'], 'generates globally-unique ids with prefix');

    t.end();
});

Estimated bundle size increase

~95 B (details)

Dependencies

(none)

none

amp-create-callback

amp-create-callback

v1.0.1

Docs

Internal amp utility for creating callbacks used in looping functions such as map and filter (mainly used internally). Having a known argument count makes it more optimizable by browsers.

Example Usage

var createCallback = require('amp-create-callback');

var callback = createCallback(function () {
    // something
}, context, 3);

[1, 2, 3].map(callback);
module.exports = function createCallback(func, context, argCount) {
    if (context === void 0) return func;
    switch (argCount) {
    case 1: 
        return function(value) {
            return func.call(context, value);
        };
    case 2: 
        return function(value, other) {
            return func.call(context, value, other);
        };
    case 3: 
        return function(value, index, collection) {
            return func.call(context, value, index, collection);
        };
    case 4: 
        return function(accumulator, value, index, collection) {
            return func.call(context, accumulator, value, index, collection);
        };
    }
    return function() {
        return func.apply(context, arguments);
    };
};
var test = require('tape');
var createCallback = require('./create-callback');


test('amp-create-callback', function (t) {
    var argLength = 1;
    var context = {hi: 'there'};

    var callback = createCallback(function () {
        t.equal(this, context, 'should maintain context');
        t.equal(arguments.length, 1, 'should never have more than arg length passed');
    }, context, 1);
    callback(1, 2, 3, 4, 5);

    callback = createCallback(function () {
        t.equal(this, context, 'should maintain context');
        t.equal(arguments.length, 2, 'should never have more than arg length passed');
    }, context, 2);
    callback(1, 2, 3, 4, 5);

    callback = createCallback(function () {
        t.equal(this, context, 'should maintain context');
        t.equal(arguments.length, 3, 'should never have more than arg length passed');
    }, context, 3);
    callback(1, 2, 3, 4, 5);

    callback = createCallback(function () {
        t.equal(this, context, 'should maintain context');
        t.equal(arguments.length, 4, 'should never have more than arg length passed');
    }, context, 4);
    callback(1, 2, 3, 4, 5);
    
    callback = createCallback(function () {
        t.equal(arguments.length, 5, 'should have as many as passed');
    });
    callback(1, 2, 3, 4, 5);
    
    t.end();
});

Estimated bundle size increase

~98 B (details)

Dependencies

(none)

none

amp-internal-flatten

amp-internal-flatten

v1.0.1

Docs

An internal flatten implementation for re-use.

Takes following args:

  • value: initial array
  • shallow: whether to flatten recursively or just one level
  • strict: if strict is true it won't keep any values other than arrays an arguments
  • output: array or array-like object we're pushing to and will return

Example Usage

var internalFlatten = require('amp-internal-flatten');

var arr = [1, [1], [[1]], 'something'];

// shallow
internalFlatten(arr, true, false, []); 
//=> [1, 1, [1], 'something'];

// recursive
internalFlatten(arr, false, false, []); 
//=> [1, 1, 1, 'something'];

// recursive + strict 
// these options *always* will
// result an empty array as output
internalFlatten(arr, false, true, []); 
//=> [];

// shallow + strict
// any non-arrays are removed
// but only run through once
// so only 2ns and 3rd args make it
// but are flattened one level
internalFlatten(arr, true, true, []); 
//=> [1, [1]];
var isArray = require('amp-is-array');
var isArguments = require('amp-is-arguments');


var flatten = function flatten(input, shallow, strict, startIndex) {
    var output = [], idx = 0, value;
    for (var i = startIndex || 0, length = input && input.length; i < length; i++) {
        value = input[i];
        if (value && value.length >= 0 && (isArray(value) || isArguments(value))) {
            //flatten current level of array or arguments object
            if (!shallow) value = flatten(value, shallow, strict);
            var j = 0, len = value.length;
            output.length += len;
            while (j < len) {
                output[idx++] = value[j++];
            }
        } else if (!strict) {
            output[idx++] = value;
        }
    }
    return output;
};

module.exports = flatten;
var test = require('tape');
var flatten = require('./internal-flatten');


test('amp-internal-flatten', function (t) {
    var arr = [1, [1], [[1]], 'something'];

    t.deepEqual(flatten(arr, true, false), [1, 1, [1], 'something'], 'shallow');
    t.deepEqual(flatten(arr, false, false), [1, 1, 1, 'something'], 'recursive');
    t.deepEqual(flatten(arr, false, true), [], 'recursive + strict');
    t.deepEqual(flatten(arr, true, true), [1, [1]], 'shallow + strict');

    t.end();
});

Estimated bundle size increase

~260 B (details)

Dependencies