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:
1.x.x
versionMany 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.
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.
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.
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>';
~408 B (details)
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.
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
~131 B (details)
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.
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>';
~357 B (details)
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.
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>';
~717 B (details)
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.
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
~307 B (details)
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.
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'
~148 B (details)
none
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?".
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!'
~345 B (details)
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.
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
~45 B (details)
none
Returns a new negated version of the predicate function.
var negate = require('amp-negate');
negate(function() { return true; }); //=> false
negate(function() { return false; }); //=> true
~29 B (details)
none
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.
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
~82 B (details)
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.
var times = require('amp-times');
var timesCalled = 0;
var logCalls = function () {
console.log(timesCalled);
return ++timesCalled;
};
times(2, logCalls);
//=> 0
//=> 1
~178 B (details)
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.
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
~484 B (details)
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)
.
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'}
~583 B (details)
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.
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
~867 B (details)
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.
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}]
~921 B (details)
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.
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}
~919 B (details)
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.
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
~939 B (details)
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.
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]
~868 B (details)
Extracts the named value of a property from every item in a collection and returns them in an array.
var pluck = require('amp-pluck');
var items = [{name: 'Cog', price: 100}, {name: 'Sprocket', price: 99}];
pluck(items, 'name'); //=> ['Cog', 'Sprocket']
~898 B (details)
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.
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
~651 B (details)
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.
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}]
~986 B (details)
Returns n random values from a collection. If n is not specified, returns a single random element.
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
~626 B (details)
Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle.
var shuffle = require('amp-shuffle');
shuffle([1, 2, 3, 4, 5, 6]);// [2, 5, 1, 6, 1, 4], sometimes
~560 B (details)
Return the number of values in the list or keys (if you pass it an object).
var size = require('amp-size');
size([1, 2, 3]); //=> 3
size({hi: 'there', oh: 'hello there'}); //=> 2
~420 B (details)
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.
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
~863 B (details)
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
).
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' } ]
~1.01 kB (details)
Creates a real Array
from the list (anything that can be iterated over).
var toArray = require('amp-to-array');
(function(){ return toArray(arguments).slice(1); })(1, 2, 3, 4);// [2, 3, 4]
~977 B (details)
Returns a copy of the array with all falsy values removed. This includes false
, null
, 0
, ""
, undefined
and NaN
.
var compact = require('amp-compact');
console.log(contains([0, 1, false, 2, false, 3])); //=> [1, 2, 3]
~945 B (details)
Returns all the values from the array that are not present in any of the other arrays.
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]
~1.25 kB (details)
Returns the first item(s) in an array. Passing n will return the first n items in the array. Also works on arguments
.
var first = require('amp-first');
first([1, 2, 3]); //=> 1
first([1, 2, 3], 2); //=> [1, 2]
~58 B (details)
none
Flattens a nested array (the nesting can be to any depth). If you pass shallow
, the array will only be flattened a single level.
var flatten = require('amp-flatten');
flatten([1, [2], [3, [[4]]]]);
//=> [1, 2, 3, 4];
flatten([1, [2], [3, [[4]]]], true);
//=> [1, 2, 3, [[4]]];
~299 B (details)
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.
var indexOf = require('amp-index-of');
indexOf(['oh', 'hello', 'there'], 'hello'); //=> 1
indexOf(['hi', 'there'], 'hello'); //=> -1
~130 B (details)
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
.
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]
~571 B (details)
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.
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
~284 B (details)
Returns the last item(s) in an array. Passing n will return the last n items in the array. Also works on arguments
.
var last = require('amp-last');
last([1, 2, 3]); //=> 3
last([1, 2, 3], 2); //=> [2, 3]
~65 B (details)
none
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.
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); //=> []
~86 B (details)
none
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.
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
~853 B (details)
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.
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}]
~905 B (details)
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.
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]
~1.27 kB (details)
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.
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'}
//=> ]
~1.01 kB (details)
Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.
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
~219 B (details)
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.
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'
// }
~118 B (details)
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.
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'
// }
~111 B (details)
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.
var has = require('amp-has');
var obj = {
greeting: 'Oh, hello there!'
};
has(obj, 'greeting'); //=> true
has(obj, 'hasOwnProperty'); //=> false
~43 B (details)
none
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.
var invert = require('amp-invert');
var person = {
favoriteColor: 'magenta',
favoriteFood: 'swedish pancakes'
};
invert(person);
//=>
// {
// magenta: 'favoriteColor',
// 'swedish pancakes': 'favoriteFood'
// }
~429 B (details)
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 []
.
var keys = require('amp-keys');
var obj = {
hi: 'there',
oh: 'hello there'
};
keys(obj); //=> ['hi', 'oh']
keys(undefined) //=> []
~383 B (details)
Returns a function that will tell you if a passed in object contains all of the key/value properties present in passed attributeObject
.
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}
//=> ]
~520 B (details)
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.
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'
// }
~166 B (details)
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.
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'}
~1.35 kB (details)
Convert an object into a list of [key, value]
pairs.
var pairs = require('amp-pairs');
var obj = {one: 1, two: 2, three: 3};
pairs(obj); //=> [["one", 1], ["two", 2], ["three", 3]]
~442 B (details)
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.
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}
~555 B (details)
Returns a function that will itself return the given propertyName
of any passed-in object. Useful when iterating collections.
var property = require('amp-property');
var greetingGetter = property('greeting');
var person = {greeting: 'oh, hello!'};
greetingGetter(person); //=> 'oh, hello!'
~27 B (details)
none
Returns all the values of an object's properties as an array.
var values = require('amp-values');
var obj = {
hi: 'there',
hello: 'you'
};
values(obj); //=> ['there', 'you']
~438 B (details)
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.
var escape = require('amp-escape');
var htmlString = '<b>HI</b>';
var escaped = escape(htmlString); //=> '<b>HI</b>'
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); //=> '<b>HI</b>'
escaper.unescape(escaped); //=> '<b>HI</b>'
~572 B (details)
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.
var includes = require('amp-includes');
var myString = 'Oh, hello there!';
includes(myString, 'hello'); //=> true
includes(myString, 'hello', 10); //=> false
includes(myString, 'hi'); //=> false
~37 B (details)
none
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.
var toCamelCase = require('amp-to-camel-case');
toCamelCase('hi there'); //=> "hiThere"
toCamelCase('oh hello there', true); //=> "OhHelloThere"
~162 B (details)
Removes whitespace from both ends of the string.
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!'
~43 B (details)
none
Takes an array
of values and returns a readable string separated with comma and conjunction
if length warrants it.
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'
~119 B (details)
none
Returns true
if passed value is an arguments
object and false
for everything else.
var isArguments = require('amp-is-arguments');
isArguments(arguments); //=> true
isArguments([]); //=> false
~89 B (details)
none
Returns true
if passed value is an Array
and false
for everything else. Uses native Array.isArray
if available.
var isArray = require('amp-is-array');
isArray([]); //=> true
isArray([1, 2, 3]); //=> true
isArray(arguments); //=> false
~54 B (details)
none
Returns true
if passed value is true
or false
. Returns false
for everything else.
var isBoolean = require('amp-is-boolean');
isBoolean(true); //=> true
isBoolean(false); //=> true
isBoolean(0); //=> false
~55 B (details)
none
Returns true
if passed value is a Date
and false
for everything else.
var isDate = require('amp-is-date');
isDate(new Date()); //=> true
~42 B (details)
none
Returns true
if passed an "empty" value and false
for everything else.
Empty is defined as:
{}
[]
''
undefined
null
NaN
0
var isEmpty = require('amp-is-empty');
isEmpty({}); //=> true
isEmpty([]); //=> true
isEmpty(''); //=> true
isEmpty(0); //=> true
isEmpty(null); //=> true
isEmpty(undefined); //=> true
isEmpty(NaN); //=> true
~601 B (details)
Returns true
if passed value is a Function
and false
for everything else.
var isFunction = require('amp-is-function');
isFunction(function () {}); //=> true
isFunction({}); //=> false
~65 B (details)
none
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.
var isNan = require('amp-is-nan');
isNan(NaN); //=> true
isNan(undefined); //=> false
isNan(0); //=> false
~77 B (details)
Returns true
if passed value is null
and false
for everything else.
var isNull = require('amp-is-null');
isNull(null); //=> true
isNull('anything else'); //=> false
~14 B (details)
none
Returns true
if passed value is a number and false
for everything else.
var isNumber = require('amp-is-number');
isNumber(5); //=> true
isNumber(Infinity); //=> true
isNumber('5'); //=> false
~44 B (details)
none
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.
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
~29 B (details)
none
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
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
~810 B (details)
Returns true
if passed value is a a regular expression and false
for everything else.
var isRegexp = require('amp-is-regexp');
isRegexp(/oh hello there/); //=> true
isRegexp(new RegExp('oh hello there')); //=> true
~45 B (details)
none
Returns true
if passed value is a string (including empty string) and false
for everything else.
var isString = require('amp-is-string');
isString('oh, hello there!'); //=> true
isString(''); //=> true
isString(5); //=> false
~41 B (details)
none
Returns true
if passed value is undefined
and false
for everything else (including other falsy values, null, and NaN).
var isUndefined = require('amp-is-undefined');
isUndefined(null); //=> false
isUndefined(NaN); //=> false
isUndefined(undefined); //=> true
~15 B (details)
none
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.
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;
};
~774 B (details)
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
.
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`)
~43 B (details)
none
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.
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'
~137 B (details)
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).
var uniqueId = require('amp-unique-id');
uniqueId(); //=> "1"
uniqueId('hi_'); //=> "hi_2"
~95 B (details)
none
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.
var createCallback = require('amp-create-callback');
var callback = createCallback(function () {
// something
}, context, 3);
[1, 2, 3].map(callback);
~98 B (details)
none
An internal flatten
implementation for re-use.
Takes following args:
value
: initial arrayshallow
: whether to flatten recursively or just one levelstrict
: if strict is true
it won't keep any values other than arrays an argumentsoutput
: array or array-like object we're pushing to and will returnvar 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]];
~260 B (details)