This commit is contained in:
2022-04-07 18:09:31 +05:30
parent 36ea86d8e6
commit 1c779ef816
14095 changed files with 1769361 additions and 47 deletions
+24
View File
@@ -0,0 +1,24 @@
module.exports = {
extends: 'airbnb-base',
parserOptions: {
sourceType: 'script',
},
plugins: [
'import',
'markdown',
],
rules: {
'curly': [
'error',
'all',
],
'brace-style': [
'error',
'1tbs',
{ 'allowSingleLine': false },
],
'no-console': 'error',
'no-ternary': 'error',
'newline-before-return': 'error',
},
};
+18
View File
@@ -0,0 +1,18 @@
language: node_js
node_js:
- '16'
- '14'
- '12'
- '10'
- '8'
- '6'
script:
- npm run eslint:strict
- npm run coverage
notifications:
email:
on_success: never
on_failure: always
+378
View File
@@ -0,0 +1,378 @@
# 4.19.0
## Bug fixes
## Methods
#### ``flatten()``
- Now properly flattens an object with multiple objects. [Issue](https://github.com/ecrmnn/collect.js/issues/240)
# 4.18.8
## Bug fixes
## Methods
#### ``shift()``
- Calling `shift()` on an empty collection returns null in all cases
#### ``sortKeysDesc()``
- Now works correctly when collections is an object
#### ``min()``
- Passing an array of object where not every element contains the given key no longer causes an error
#### ``max()``
- Passing an array of object where not every element contains the given key no longer causes an error
# 4.16.0
## Breaking changes
## Methods
#### ``sortBy()``
- Null values, ``null`` and ``undefined`` will be sorted last, like normal ``.sort()``
# 4.14.0
## Breaking changes
## Methods
#### ``values()``
- Reverted change in `4.13.0`. Values method are no longer recursive.
# 4.14.0
## Breaking changes
## Methods
#### ``where()``
- This method now supports one, two or three arguments. This may cause unexpected output if you're using this function with one or two arguments earlier.
# 4.13.0
## Breaking changes
## Methods
#### ``values()``
- Values now iterates the collection recursively and collects values. Results that previously would return an object may now return an array.
# 4.12.0
## Breaking changes
## Collection
#### ``collect()``
- A collection instance made from an empty string is no longer recognized as an empty collection ``collect('')``
```js
// Before 4.12.0
collect('').isEmpty();
//=> true
// After 4.12.0
collect('').isEmpty();
//=> false
```
# 4.4.0
## Breaking changes
## Methods
#### ``concat()``
- Concat now returns a new collection instead of modifying the existing one
# 4.3.0
## Breaking changes
## Methods
#### ``random()``
- Previously ``random()`` and ``random(1)`` would return an array, while passing an integer >1 would return a collection object.
- ``random(1)`` now returns a collection object
- Changed ``random()`` according to https://github.com/ecrmnn/collect.js/issues/202
# 4.2.0
- Added ``whenEmpty()`` method
- Added ``whenNotEmpty()`` method
- Added ``unlessEmpty()`` method
- Added ``unlessNotEmpty()`` method
# 4.1.0
## Breaking changes
## Methods
#### ``flatMap()``
- Changed ``flatMap()`` according to https://github.com/ecrmnn/collect.js/issues/195
# 4.0.1
- Added build files so it's no longer required to use npm for installation
# 4.0.0
## Breaking changes
- ``chunk()``
- ``count()``
- ``dump()``
- ``flatMap()``
- ``has()``
- ``keys()``
- ``groupBy()``
- ``partition()``
- ``pluck()``
- ``split()``
- ``toArray()``
- ``toJson()``
- ``wrap()``
## Node.js
Skipped Node 4 support
## Methods
#### ``chunk()``
- Returns a new collection of smaller collections of the given size.
This is done because ``collect.js`` should give the same result as Laravel Collections.
- Also works when the collection is based on an object, a string, a number or boolean.
#### ``combine()``
- Also works when the collection is based on a string
- Also works when combining with a string or an object
- Also works when combining with another collection
#### ``count()``
- Also works when the collection is based on an object
- Return the number of keys in the object
#### ``dump()``
- Console logs the entire collection object (``this``) instead of only the items (``this.items``).
```js
const collection = collect([
{ product: 'Desk', manufacturer: 'IKEA' },
{ product: 'Chair', manufacturer: 'Herman Miller' },
{ product: 'Bookcase', manufacturer: 'IKEA' },
{ product: 'Door' },
]);
collection.pluck('product', 'manufacturer').dump();
// Prior to 4.0.0
//=> {
//=> IKEA: 'Bookcase',
//=> 'Herman Miller': 'Chair',
//=> '': 'Door'
//=> }
// After 4.0.0
//=> Collection {
//=> items: {
//=> IKEA: 'Bookcase',
//=> 'Herman Miller': 'Chair',
//=> '': 'Door'
//=> }
//=> }
```
#### ``except()``
- Accepts an array or infinite number of arguments.
#### ``first()``
- Also works when the collection is based on an object.
```js
const collection = collect({
name: 'Sadio Mané',
club: 'Liverpool FC',
});
collection.first();
//=> Sadio Mané
```
#### ``flatMap()``
- Version prior to 4.0.0 did not work as expected
- Rewritten with new functionality
- See readme for further details
#### ``flip()``
- Also works when the collection is based on an object
#### ``forget()``
- Also works when the collection is based on an object
#### ``forPage()``
- Also works when the collection is based on an object
#### ``groupBy()``
- Objects that don't have the key that we're grouping by will be grouped into a group under the
name of an empty string. This is changed from being grouped under ``undefined``.
- Now returns a collection of collections instead of an array of objects.
This is done because ``collect.js`` should give the same result as Laravel Collections.
```js
```
#### ``has()``
- Accepts an array of keys to check
- Is now a variadic function and therefore accepts infinite number of arguments (keys) to check
- No longer checks if any object in the given array has the specified key.
This is done because ``collect.js`` should give the same result as Laravel Collections.
```js
// Previously this would return true. It now returns false.
const collection = collect([{
animal: 'unicorn',
ability: 'magical'
}, {
animal: 'pig',
ability: 'filthy'
}]);
collection.has('ability');
//=> true (Prior to 4.0.0)
//=> false (After 4.0.0)
```
#### ``keyBy()``
- Uses an empty string as the key instead of ``undefined`` when passed an invalid key
#### ``keys()``
- Returns indexes as keys when based on an array. Indexes are mapped to ``Number``.
```js
const collection = collect([{
name: 'Sadio Mané',
}, {
name: 'Roberto Firmino',
}]);
const keys = collection.keys();
// Prior to 4.0.0
//=> ['name', 'name']
// After 4.0.0
//=> [0, 1]
```
#### ``last()``
- Also works when the collection is based on an object.
```js
const collection = collect({
name: 'Sadio Mané',
club: 'Liverpool FC',
});
collection.last();
//=> Liverpool FC
```
#### ``merge()``
- Can merge arrays and objects.
- Also works when merging with a string.
#### ``only()``
- Accepts an array or infinite number of arguments.
#### ``partition()``
- Returns a collection of collections with the results instead of an array
#### ``pluck()``
- Returns ``null`` as the value instead of ``undefined``
- Returns ``null`` when an item does not contain the specified key.
```js
const collection = collect([
{ product: 'Desk', manufacturer: 'IKEA' },
{ product: 'Chair', manufacturer: 'Herman Miller' },
{ product: 'Bookcase', manufacturer: 'IKEA' },
{ product: 'Door' },
]);
const pluck = collection.pluck('non-existing-key');
pluck.all();
//=> [null, null, null, null]
const manufacturers = collection.pluck('manufacturer');
manufacturers.all();
//=> ['IKEA', 'Herman Miller', 'IKEA', null]
```
- Objects that don't have the key that we're plucking by will get an empty string as its key.
This is changed from being ``undefined``.
```js
const collection = collect([
{ product: 'Desk', manufacturer: 'IKEA' },
{ product: 'Chair', manufacturer: 'Herman Miller' },
{ product: 'Bookcase', manufacturer: 'IKEA' },
{ product: 'Door' },
]);
const pluck = collection.pluck('product', 'manufacturer');
pluck.all();
//=> {
//=> IKEA: 'Bookcase',
//=> 'Herman Miller': 'Chair',
//=> '': 'Door',
//=> }
```
#### ``pop()``
- Also works when collection is based on an object
#### ``push()``
- Accepts spread/rest operator ``collection.push(...values)``
#### ``random()``
- Also works when collection is based on an object
#### ``shift()``
- Also works when collection is based on an object
#### ``shuffle()``
- Also works when collection is based on an object
#### ``split()``
- Splits the collection into the given number of collections
```js
const collection = collect([1, 2, 3, 4, 5]);
collection.split(2).dump();
// Prior to 4.0.0
//=> [
//=> [1, 2, 3],
//=> [4, 5],
//=> ]
// After 4.0.0
//=> Collection {
//=> items: {
//=> Collection {
//=> items: [1, 2, 3]
//=> },
//=> Collection {
//=> items: [4, 5]
//=> },
//=> }
//=> }
```
#### ``take()``
- Also works when collection is based on an object
#### ``toArray()``
- Now works recursively like Laravel collections ``toArray()`` method
- More information: https://github.com/ecrmnn/collect.js/issues/138
#### ``toJson()``
- Now works recursively like Laravel collections ``toArray()`` method
- More information: https://github.com/ecrmnn/collect.js/issues/138
#### ``wrap()``
- Now wraps objects correctly. The key/values are places directly on the collection. Previously objects were wrapped in
an array.
## Misc
- Added ``CHANGELOG.md``
+16
View File
@@ -0,0 +1,16 @@
# Contribution Guidelines
By participating in this project you agree to abide by its terms.
---
Ensure your pull request adheres to the following guidelines:
- For bug fixes or improvements please describe what your PR solves
- If you're adding a new method please link to the Laravel implementation of the same method
- PRs without tests will not be considered
- Check your spelling and grammar
- Adhere to the AirBnB JavaScript style guide
- Make sure your text editor is set to remove trailing whitespace.
Thank you for your contributions!
Generated Vendored Executable
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Daniel Eckermann
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3251
View File
File diff suppressed because it is too large Load Diff
+1613
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
### API
All available methods
+8
View File
@@ -0,0 +1,8 @@
[![Travis](https://img.shields.io/travis/com/ecrmnn/collect.js?style=flat-square)](https://app.travis-ci.com/github/ecrmnn/collect.js/builds)
[![npm version](https://img.shields.io/npm/v/collect.js.svg?style=flat-square)](http://badge.fury.io/js/collect.js)
[![npm downloads](https://img.shields.io/npm/dm/collect.js.svg?style=flat-square)](http://badge.fury.io/js/collect.js)
[![npm license](https://img.shields.io/npm/l/collect.js.svg?style=flat-square)](http://badge.fury.io/js/collect.js)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
[![dependencies](https://img.shields.io/badge/dependencies-none-brightgreen.svg?style=flat-square)](https://github.com/ecrmnn/collect.js/blob/master/package.json)
[![eslint](https://img.shields.io/badge/code_style-airbnb-blue.svg?style=flat-square)](https://github.com/airbnb/javascript)
[![cdnjs version](https://img.shields.io/cdnjs/v/collect.js.svg?style=flat-square)](https://cdnjs.com/libraries/collect.js)
+55
View File
@@ -0,0 +1,55 @@
'use strict';
const { readFileSync, readdirSync, writeFileSync } = require('fs');
// Get all markdown stubs
const header = readFileSync('bundler/header.md', 'utf-8');
const badges = readFileSync('bundler/badges.md', 'utf-8');
const installation = readFileSync('bundler/installation.md', 'utf-8');
const api = readFileSync('bundler/api.md', 'utf-8');
const strictnessAndComparisons = readFileSync('bundler/strictness_and_comparisons.md', 'utf-8');
const notImplemented = readFileSync('bundler/not_implemented.md', 'utf-8');
const contribute = readFileSync('bundler/contribute.md', 'utf-8');
const license = readFileSync('bundler/license.md', 'utf-8');
// Get all API docs
const methods = readdirSync('docs/api', 'utf-8');
// Build table of contents
const tableOfContents = methods.map((file) => {
const methodName = file.replace('.md', '');
return `- [${methodName}](#${methodName.toLowerCase()})`;
}).join('\n');
// Build methods "readme"
const methodDocumentation = methods.map((file) => {
let content = readFileSync(`docs/api/${file}`, 'utf-8');
const lines = content.split('\n');
lines[0] = `###${lines[0]}`;
lines.pop();
lines.pop();
content = lines.join('\n');
content = content.replace(/(\r\n|\r|\n){2,}/g, '$1\n');
return content;
}).join('\n\n');
writeFileSync(
'README.md',
[
header,
badges,
installation,
api,
tableOfContents,
strictnessAndComparisons,
notImplemented,
methodDocumentation,
contribute,
license,
].join('\n\n'),
);
+3
View File
@@ -0,0 +1,3 @@
### Contribute
PRs are welcomed to this project, and help is needed in order to keep up with the changes of Laravel Collections. If you want to improve the collection library, add functionality or improve the docs please feel free to submit a PR.
+3
View File
@@ -0,0 +1,3 @@
# <img src="https://raw.githubusercontent.com/ecrmnn/collect.js/master/collectjs.jpg" alt="collect.js">
> Convenient and dependency free wrapper for working with arrays and objects
+27
View File
@@ -0,0 +1,27 @@
### Installation
#### NPM
```bash
npm install collect.js --save
```
#### Yarn
```bash
yarn add collect.js
```
#### From CDN
1. Visit https://cdnjs.com/libraries/collect.js
2. Add CDN link to your site with `<script>`
#### Using build / minified version
1. Download [`collect.min.js`](https://github.com/ecrmnn/collect.js/blob/master/build/collect.min.js)
2. Add to your site with `<script>`
### Tip
Using Laravel as your backend? Collect.js offers an (almost) identical api to [Laravel Collections](https://laravel.com/docs/master/collections). [See differences](#strictness-and-comparisons).
+3
View File
@@ -0,0 +1,3 @@
### License
MIT © [Daniel Eckermann](https://danieleckermann.com)
+8
View File
@@ -0,0 +1,8 @@
##### Methods that have not been implemented:
- ~~`containsStrict`~~ use `contains()`
- ~~`duplicatesStrict`~~ use `duplicates()`
- ~~`uniqueStrict`~~ use `unique()`
- ~~`whereStrict`~~ use `where()`
- ~~`whereInStrict`~~ use `whereIn()`
- ~~`whereNotInStrict`~~ use `whereNotIn()`
@@ -0,0 +1,3 @@
### Strictness and comparisons
All comparisons in `collect.js` are done using strict equality. Using loose equality comparisons are generally frowned upon in JavaScript. Laravel only performs "loose" comparisons by default and offer several "strict" comparison methods. These methods have not been implemented in `collect.js` because all methods are strict by default.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

+32
View File
@@ -0,0 +1,32 @@
'use strict';
/**
* Clone helper
*
* Clone an array or object
*
* @param items
* @returns {*}
*/
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
module.exports = function clone(items) {
var cloned = void 0;
if (Array.isArray(items)) {
var _cloned;
cloned = [];
(_cloned = cloned).push.apply(_cloned, _toConsumableArray(items));
} else {
cloned = {};
Object.keys(items).forEach(function (prop) {
cloned[prop] = items[prop];
});
}
return cloned;
};
+23
View File
@@ -0,0 +1,23 @@
'use strict';
var variadic = require('./variadic');
/**
* Delete keys helper
*
* Delete one or multiple keys from an object
*
* @param obj
* @param keys
* @returns {void}
*/
module.exports = function deleteKeys(obj) {
for (var _len = arguments.length, keys = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
keys[_key - 1] = arguments[_key];
}
variadic(keys).forEach(function (key) {
// eslint-disable-next-line
delete obj[key];
});
};
+26
View File
@@ -0,0 +1,26 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
module.exports = {
/**
* @returns {boolean}
*/
isArray: function isArray(item) {
return Array.isArray(item);
},
/**
* @returns {boolean}
*/
isObject: function isObject(item) {
return (typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object' && Array.isArray(item) === false && item !== null;
},
/**
* @returns {boolean}
*/
isFunction: function isFunction(item) {
return typeof item === 'function';
}
};
+20
View File
@@ -0,0 +1,20 @@
'use strict';
/**
* Get value of a nested property
*
* @param mainObject
* @param key
* @returns {*}
*/
module.exports = function nestedValue(mainObject, key) {
try {
return key.split('.').reduce(function (obj, property) {
return obj[property];
}, mainObject);
} catch (err) {
// If we end up here, we're not working with an object, and @var mainObject is the value itself
return mainObject;
}
};
+28
View File
@@ -0,0 +1,28 @@
'use strict';
/**
* Values helper
*
* Retrieve values from [this.items] when it is an array, object or Collection
*
* @param items
* @returns {*}
*/
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
module.exports = function values(items) {
var valuesArray = [];
if (Array.isArray(items)) {
valuesArray.push.apply(valuesArray, _toConsumableArray(items));
} else if (items.constructor.name === 'Collection') {
valuesArray.push.apply(valuesArray, _toConsumableArray(items.all()));
} else {
Object.keys(items).forEach(function (prop) {
return valuesArray.push(items[prop]);
});
}
return valuesArray;
};
+16
View File
@@ -0,0 +1,16 @@
'use strict';
/**
* Variadic helper function
*
* @param args
* @returns {Array}
*/
module.exports = function variadic(args) {
if (Array.isArray(args[0])) {
return args[0];
}
return args;
};
+161
View File
@@ -0,0 +1,161 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function Collection(collection) {
if (collection !== undefined && !Array.isArray(collection) && (typeof collection === 'undefined' ? 'undefined' : _typeof(collection)) !== 'object') {
this.items = [collection];
} else if (collection instanceof this.constructor) {
this.items = collection.all();
} else {
this.items = collection || [];
}
}
/**
* Symbol.iterator
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator
*/
var SymbolIterator = require('./methods/symbol.iterator');
if (typeof Symbol !== 'undefined') {
Collection.prototype[Symbol.iterator] = SymbolIterator;
}
/**
* Support JSON.stringify
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
*/
Collection.prototype.toJSON = function toJSON() {
return this.items;
};
Collection.prototype.all = require('./methods/all');
Collection.prototype.average = require('./methods/average');
Collection.prototype.avg = require('./methods/avg');
Collection.prototype.chunk = require('./methods/chunk');
Collection.prototype.collapse = require('./methods/collapse');
Collection.prototype.combine = require('./methods/combine');
Collection.prototype.concat = require('./methods/concat');
Collection.prototype.contains = require('./methods/contains');
Collection.prototype.count = require('./methods/count');
Collection.prototype.countBy = require('./methods/countBy');
Collection.prototype.crossJoin = require('./methods/crossJoin');
Collection.prototype.dd = require('./methods/dd');
Collection.prototype.diff = require('./methods/diff');
Collection.prototype.diffAssoc = require('./methods/diffAssoc');
Collection.prototype.diffKeys = require('./methods/diffKeys');
Collection.prototype.doesntContain = require('./methods/doesntContain');
Collection.prototype.dump = require('./methods/dump');
Collection.prototype.duplicates = require('./methods/duplicates');
Collection.prototype.each = require('./methods/each');
Collection.prototype.eachSpread = require('./methods/eachSpread');
Collection.prototype.every = require('./methods/every');
Collection.prototype.except = require('./methods/except');
Collection.prototype.filter = require('./methods/filter');
Collection.prototype.first = require('./methods/first');
Collection.prototype.firstOrFail = require('./methods/firstOrFail');
Collection.prototype.firstWhere = require('./methods/firstWhere');
Collection.prototype.flatMap = require('./methods/flatMap');
Collection.prototype.flatten = require('./methods/flatten');
Collection.prototype.flip = require('./methods/flip');
Collection.prototype.forPage = require('./methods/forPage');
Collection.prototype.forget = require('./methods/forget');
Collection.prototype.get = require('./methods/get');
Collection.prototype.groupBy = require('./methods/groupBy');
Collection.prototype.has = require('./methods/has');
Collection.prototype.implode = require('./methods/implode');
Collection.prototype.intersect = require('./methods/intersect');
Collection.prototype.intersectByKeys = require('./methods/intersectByKeys');
Collection.prototype.isEmpty = require('./methods/isEmpty');
Collection.prototype.isNotEmpty = require('./methods/isNotEmpty');
Collection.prototype.join = require('./methods/join');
Collection.prototype.keyBy = require('./methods/keyBy');
Collection.prototype.keys = require('./methods/keys');
Collection.prototype.last = require('./methods/last');
Collection.prototype.macro = require('./methods/macro');
Collection.prototype.make = require('./methods/make');
Collection.prototype.map = require('./methods/map');
Collection.prototype.mapSpread = require('./methods/mapSpread');
Collection.prototype.mapToDictionary = require('./methods/mapToDictionary');
Collection.prototype.mapInto = require('./methods/mapInto');
Collection.prototype.mapToGroups = require('./methods/mapToGroups');
Collection.prototype.mapWithKeys = require('./methods/mapWithKeys');
Collection.prototype.max = require('./methods/max');
Collection.prototype.median = require('./methods/median');
Collection.prototype.merge = require('./methods/merge');
Collection.prototype.mergeRecursive = require('./methods/mergeRecursive');
Collection.prototype.min = require('./methods/min');
Collection.prototype.mode = require('./methods/mode');
Collection.prototype.nth = require('./methods/nth');
Collection.prototype.only = require('./methods/only');
Collection.prototype.pad = require('./methods/pad');
Collection.prototype.partition = require('./methods/partition');
Collection.prototype.pipe = require('./methods/pipe');
Collection.prototype.pluck = require('./methods/pluck');
Collection.prototype.pop = require('./methods/pop');
Collection.prototype.prepend = require('./methods/prepend');
Collection.prototype.pull = require('./methods/pull');
Collection.prototype.push = require('./methods/push');
Collection.prototype.put = require('./methods/put');
Collection.prototype.random = require('./methods/random');
Collection.prototype.reduce = require('./methods/reduce');
Collection.prototype.reject = require('./methods/reject');
Collection.prototype.replace = require('./methods/replace');
Collection.prototype.replaceRecursive = require('./methods/replaceRecursive');
Collection.prototype.reverse = require('./methods/reverse');
Collection.prototype.search = require('./methods/search');
Collection.prototype.shift = require('./methods/shift');
Collection.prototype.shuffle = require('./methods/shuffle');
Collection.prototype.skip = require('./methods/skip');
Collection.prototype.skipUntil = require('./methods/skipUntil');
Collection.prototype.skipWhile = require('./methods/skipWhile');
Collection.prototype.slice = require('./methods/slice');
Collection.prototype.sole = require('./methods/sole');
Collection.prototype.some = require('./methods/some');
Collection.prototype.sort = require('./methods/sort');
Collection.prototype.sortDesc = require('./methods/sortDesc');
Collection.prototype.sortBy = require('./methods/sortBy');
Collection.prototype.sortByDesc = require('./methods/sortByDesc');
Collection.prototype.sortKeys = require('./methods/sortKeys');
Collection.prototype.sortKeysDesc = require('./methods/sortKeysDesc');
Collection.prototype.splice = require('./methods/splice');
Collection.prototype.split = require('./methods/split');
Collection.prototype.sum = require('./methods/sum');
Collection.prototype.take = require('./methods/take');
Collection.prototype.takeUntil = require('./methods/takeUntil');
Collection.prototype.takeWhile = require('./methods/takeWhile');
Collection.prototype.tap = require('./methods/tap');
Collection.prototype.times = require('./methods/times');
Collection.prototype.toArray = require('./methods/toArray');
Collection.prototype.toJson = require('./methods/toJson');
Collection.prototype.transform = require('./methods/transform');
Collection.prototype.unless = require('./methods/unless');
Collection.prototype.unlessEmpty = require('./methods/whenNotEmpty');
Collection.prototype.unlessNotEmpty = require('./methods/whenEmpty');
Collection.prototype.union = require('./methods/union');
Collection.prototype.unique = require('./methods/unique');
Collection.prototype.unwrap = require('./methods/unwrap');
Collection.prototype.values = require('./methods/values');
Collection.prototype.when = require('./methods/when');
Collection.prototype.whenEmpty = require('./methods/whenEmpty');
Collection.prototype.whenNotEmpty = require('./methods/whenNotEmpty');
Collection.prototype.where = require('./methods/where');
Collection.prototype.whereBetween = require('./methods/whereBetween');
Collection.prototype.whereIn = require('./methods/whereIn');
Collection.prototype.whereInstanceOf = require('./methods/whereInstanceOf');
Collection.prototype.whereNotBetween = require('./methods/whereNotBetween');
Collection.prototype.whereNotIn = require('./methods/whereNotIn');
Collection.prototype.whereNull = require('./methods/whereNull');
Collection.prototype.whereNotNull = require('./methods/whereNotNull');
Collection.prototype.wrap = require('./methods/wrap');
Collection.prototype.zip = require('./methods/zip');
var collect = function collect(collection) {
return new Collection(collection);
};
module.exports = collect;
module.exports.collect = collect;
module.exports.default = collect;
module.exports.Collection = Collection;
+5
View File
@@ -0,0 +1,5 @@
'use strict';
module.exports = function all() {
return this.items;
};
+16
View File
@@ -0,0 +1,16 @@
'use strict';
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function average(key) {
if (key === undefined) {
return this.sum() / this.items.length;
}
if (isFunction(key)) {
return new this.constructor(this.items).sum(key) / this.items.length;
}
return new this.constructor(this.items).pluck(key).sum() / this.items.length;
};
+5
View File
@@ -0,0 +1,5 @@
'use strict';
var average = require('./average');
module.exports = average;
+42
View File
@@ -0,0 +1,42 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
module.exports = function chunk(size) {
var _this = this;
var chunks = [];
var index = 0;
if (Array.isArray(this.items)) {
do {
var items = this.items.slice(index, index + size);
var collection = new this.constructor(items);
chunks.push(collection);
index += size;
} while (index < this.items.length);
} else if (_typeof(this.items) === 'object') {
var keys = Object.keys(this.items);
var _loop = function _loop() {
var keysOfChunk = keys.slice(index, index + size);
var collection = new _this.constructor({});
keysOfChunk.forEach(function (key) {
return collection.put(key, _this.items[key]);
});
chunks.push(collection);
index += size;
};
do {
_loop();
} while (index < keys.length);
} else {
chunks.push(new this.constructor([this.items]));
}
return new this.constructor(chunks);
};
+9
View File
@@ -0,0 +1,9 @@
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
module.exports = function collapse() {
var _ref;
return new this.constructor((_ref = []).concat.apply(_ref, _toConsumableArray(this.items)));
};
+39
View File
@@ -0,0 +1,39 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
module.exports = function combine(array) {
var _this = this;
var values = array;
if (values instanceof this.constructor) {
values = array.all();
}
var collection = {};
if (Array.isArray(this.items) && Array.isArray(values)) {
this.items.forEach(function (key, iterator) {
collection[key] = values[iterator];
});
} else if (_typeof(this.items) === 'object' && (typeof values === 'undefined' ? 'undefined' : _typeof(values)) === 'object') {
Object.keys(this.items).forEach(function (key, index) {
collection[_this.items[key]] = values[Object.keys(values)[index]];
});
} else if (Array.isArray(this.items)) {
collection[this.items[0]] = values;
} else if (typeof this.items === 'string' && Array.isArray(values)) {
var _values = values;
var _values2 = _slicedToArray(_values, 1);
collection[this.items] = _values2[0];
} else if (typeof this.items === 'string') {
collection[this.items] = values;
}
return new this.constructor(collection);
};
+32
View File
@@ -0,0 +1,32 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var clone = require('../helpers/clone');
module.exports = function concat(collectionOrArrayOrObject) {
var list = collectionOrArrayOrObject;
if (collectionOrArrayOrObject instanceof this.constructor) {
list = collectionOrArrayOrObject.all();
} else if ((typeof collectionOrArrayOrObject === 'undefined' ? 'undefined' : _typeof(collectionOrArrayOrObject)) === 'object') {
list = [];
Object.keys(collectionOrArrayOrObject).forEach(function (property) {
list.push(collectionOrArrayOrObject[property]);
});
}
var collection = clone(this.items);
list.forEach(function (item) {
if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object') {
Object.keys(item).forEach(function (key) {
return collection.push(item[key]);
});
} else {
collection.push(item);
}
});
return new this.constructor(collection);
};
+35
View File
@@ -0,0 +1,35 @@
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var values = require('../helpers/values');
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function contains(key, value) {
if (value !== undefined) {
if (Array.isArray(this.items)) {
return this.items.filter(function (items) {
return items[key] !== undefined && items[key] === value;
}).length > 0;
}
return this.items[key] !== undefined && this.items[key] === value;
}
if (isFunction(key)) {
return this.items.filter(function (item, index) {
return key(item, index);
}).length > 0;
}
if (Array.isArray(this.items)) {
return this.items.indexOf(key) !== -1;
}
var keysAndValues = values(this.items);
keysAndValues.push.apply(keysAndValues, _toConsumableArray(Object.keys(this.items)));
return keysAndValues.indexOf(key) !== -1;
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
module.exports = function count() {
var arrayLength = 0;
if (Array.isArray(this.items)) {
arrayLength = this.items.length;
}
return Math.max(Object.keys(this.items).length, arrayLength);
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
module.exports = function countBy() {
var fn = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function (value) {
return value;
};
return new this.constructor(this.items).groupBy(fn).map(function (value) {
return value.count();
});
};
+34
View File
@@ -0,0 +1,34 @@
'use strict';
module.exports = function crossJoin() {
function join(collection, constructor, args) {
var current = args[0];
if (current instanceof constructor) {
current = current.all();
}
var rest = args.slice(1);
var last = !rest.length;
var result = [];
for (var i = 0; i < current.length; i += 1) {
var collectionCopy = collection.slice();
collectionCopy.push(current[i]);
if (last) {
result.push(collectionCopy);
} else {
result = result.concat(join(collectionCopy, constructor, rest));
}
}
return result;
}
for (var _len = arguments.length, values = Array(_len), _key = 0; _key < _len; _key++) {
values[_key] = arguments[_key];
}
return new this.constructor(join([], this.constructor, [].concat([this.items], values)));
};
+9
View File
@@ -0,0 +1,9 @@
'use strict';
module.exports = function dd() {
this.dump();
if (typeof process !== 'undefined') {
process.exit(1);
}
};
+17
View File
@@ -0,0 +1,17 @@
'use strict';
module.exports = function diff(values) {
var valuesToDiff = void 0;
if (values instanceof this.constructor) {
valuesToDiff = values.all();
} else {
valuesToDiff = values;
}
var collection = this.items.filter(function (item) {
return valuesToDiff.indexOf(item) === -1;
});
return new this.constructor(collection);
};
+21
View File
@@ -0,0 +1,21 @@
'use strict';
module.exports = function diffAssoc(values) {
var _this = this;
var diffValues = values;
if (values instanceof this.constructor) {
diffValues = values.all();
}
var collection = {};
Object.keys(this.items).forEach(function (key) {
if (diffValues[key] === undefined || diffValues[key] !== _this.items[key]) {
collection[key] = _this.items[key];
}
});
return new this.constructor(collection);
};
+19
View File
@@ -0,0 +1,19 @@
'use strict';
module.exports = function diffKeys(object) {
var objectToDiff = void 0;
if (object instanceof this.constructor) {
objectToDiff = object.all();
} else {
objectToDiff = object;
}
var objectKeys = Object.keys(objectToDiff);
var remainingKeys = Object.keys(this.items).filter(function (item) {
return objectKeys.indexOf(item) === -1;
});
return new this.constructor(this.items).only(remainingKeys);
};
+5
View File
@@ -0,0 +1,5 @@
'use strict';
module.exports = function contains(key, value) {
return !this.contains(key, value);
};
+8
View File
@@ -0,0 +1,8 @@
'use strict';
module.exports = function dump() {
// eslint-disable-next-line
console.log(this);
return this;
};
+42
View File
@@ -0,0 +1,42 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
module.exports = function duplicates() {
var _this = this;
var occuredValues = [];
var duplicateValues = {};
var stringifiedValue = function stringifiedValue(value) {
if (Array.isArray(value) || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
return JSON.stringify(value);
}
return value;
};
if (Array.isArray(this.items)) {
this.items.forEach(function (value, index) {
var valueAsString = stringifiedValue(value);
if (occuredValues.indexOf(valueAsString) === -1) {
occuredValues.push(valueAsString);
} else {
duplicateValues[index] = value;
}
});
} else if (_typeof(this.items) === 'object') {
Object.keys(this.items).forEach(function (key) {
var valueAsString = stringifiedValue(_this.items[key]);
if (occuredValues.indexOf(valueAsString) === -1) {
occuredValues.push(valueAsString);
} else {
duplicateValues[key] = _this.items[key];
}
});
}
return new this.constructor(duplicateValues);
};
+26
View File
@@ -0,0 +1,26 @@
'use strict';
module.exports = function each(fn) {
var stop = false;
if (Array.isArray(this.items)) {
var length = this.items.length;
for (var index = 0; index < length && !stop; index += 1) {
stop = fn(this.items[index], index, this.items) === false;
}
} else {
var keys = Object.keys(this.items);
var _length = keys.length;
for (var _index = 0; _index < _length && !stop; _index += 1) {
var key = keys[_index];
stop = fn(this.items[key], key, this.items) === false;
}
}
return this;
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
module.exports = function eachSpread(fn) {
this.each(function (values, key) {
fn.apply(undefined, _toConsumableArray(values).concat([key]));
});
return this;
};
+9
View File
@@ -0,0 +1,9 @@
'use strict';
var values = require('../helpers/values');
module.exports = function every(fn) {
var items = values(this.items);
return items.every(fn);
};
+31
View File
@@ -0,0 +1,31 @@
'use strict';
var variadic = require('../helpers/variadic');
module.exports = function except() {
var _this = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var properties = variadic(args);
if (Array.isArray(this.items)) {
var _collection = this.items.filter(function (item) {
return properties.indexOf(item) === -1;
});
return new this.constructor(_collection);
}
var collection = {};
Object.keys(this.items).forEach(function (property) {
if (properties.indexOf(property) === -1) {
collection[property] = _this.items[property];
}
});
return new this.constructor(collection);
};
+61
View File
@@ -0,0 +1,61 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function falsyValue(item) {
if (Array.isArray(item)) {
if (item.length) {
return false;
}
} else if (item !== undefined && item !== null && (typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object') {
if (Object.keys(item).length) {
return false;
}
} else if (item) {
return false;
}
return true;
}
function filterObject(func, items) {
var result = {};
Object.keys(items).forEach(function (key) {
if (func) {
if (func(items[key], key)) {
result[key] = items[key];
}
} else if (!falsyValue(items[key])) {
result[key] = items[key];
}
});
return result;
}
function filterArray(func, items) {
if (func) {
return items.filter(func);
}
var result = [];
for (var i = 0; i < items.length; i += 1) {
var item = items[i];
if (!falsyValue(item)) {
result.push(item);
}
}
return result;
}
module.exports = function filter(fn) {
var func = fn || false;
var filteredItems = null;
if (Array.isArray(this.items)) {
filteredItems = filterArray(func, this.items);
} else {
filteredItems = filterObject(func, this.items);
}
return new this.constructor(filteredItems);
};
+41
View File
@@ -0,0 +1,41 @@
'use strict';
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function first(fn, defaultValue) {
if (isFunction(fn)) {
var keys = Object.keys(this.items);
for (var i = 0; i < keys.length; i += 1) {
var key = keys[i];
var item = this.items[key];
if (fn(item, key)) {
return item;
}
}
if (isFunction(defaultValue)) {
return defaultValue();
}
return defaultValue;
}
if (Array.isArray(this.items) && this.items.length || Object.keys(this.items).length) {
if (Array.isArray(this.items)) {
return this.items[0];
}
var firstKey = Object.keys(this.items)[0];
return this.items[firstKey];
}
if (isFunction(defaultValue)) {
return defaultValue();
}
return defaultValue;
};
+20
View File
@@ -0,0 +1,20 @@
'use strict';
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function firstOrFail(key, operator, value) {
if (isFunction(key)) {
return this.first(key, function () {
throw new Error('Item not found.');
});
}
var collection = this.where(key, operator, value);
if (collection.isEmpty()) {
throw new Error('Item not found.');
}
return collection.first();
};
+5
View File
@@ -0,0 +1,5 @@
'use strict';
module.exports = function firstWhere(key, operator, value) {
return this.where(key, operator, value).first() || null;
};
+5
View File
@@ -0,0 +1,5 @@
'use strict';
module.exports = function flatMap(fn) {
return this.map(fn).collapse();
};
+57
View File
@@ -0,0 +1,57 @@
'use strict';
var _require = require('../helpers/is'),
isArray = _require.isArray,
isObject = _require.isObject;
module.exports = function flatten(depth) {
var flattenDepth = depth || Infinity;
var fullyFlattened = false;
var collection = [];
var flat = function flat(items) {
collection = [];
if (isArray(items)) {
items.forEach(function (item) {
if (isArray(item)) {
collection = collection.concat(item);
} else if (isObject(item)) {
Object.keys(item).forEach(function (property) {
collection = collection.concat(item[property]);
});
} else {
collection.push(item);
}
});
} else {
Object.keys(items).forEach(function (property) {
if (isArray(items[property])) {
collection = collection.concat(items[property]);
} else if (isObject(items[property])) {
Object.keys(items[property]).forEach(function (prop) {
collection = collection.concat(items[property][prop]);
});
} else {
collection.push(items[property]);
}
});
}
fullyFlattened = collection.filter(function (item) {
return isObject(item);
});
fullyFlattened = fullyFlattened.length === 0;
flattenDepth -= 1;
};
flat(this.items);
while (!fullyFlattened && flattenDepth > 0) {
flat(collection);
}
return new this.constructor(collection);
};
+19
View File
@@ -0,0 +1,19 @@
'use strict';
module.exports = function flip() {
var _this = this;
var collection = {};
if (Array.isArray(this.items)) {
Object.keys(this.items).forEach(function (key) {
collection[_this.items[key]] = Number(key);
});
} else {
Object.keys(this.items).forEach(function (key) {
collection[_this.items[key]] = key;
});
}
return new this.constructor(collection);
};
+17
View File
@@ -0,0 +1,17 @@
'use strict';
module.exports = function forPage(page, chunk) {
var _this = this;
var collection = {};
if (Array.isArray(this.items)) {
collection = this.items.slice(page * chunk - chunk, page * chunk);
} else {
Object.keys(this.items).slice(page * chunk - chunk, page * chunk).forEach(function (key) {
collection[key] = _this.items[key];
});
}
return new this.constructor(collection);
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
module.exports = function forget(key) {
if (Array.isArray(this.items)) {
this.items.splice(key, 1);
} else {
delete this.items[key];
}
return this;
};
+22
View File
@@ -0,0 +1,22 @@
'use strict';
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function get(key) {
var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (this.items[key] !== undefined) {
return this.items[key];
}
if (isFunction(defaultValue)) {
return defaultValue();
}
if (defaultValue !== null) {
return defaultValue;
}
return null;
};
+32
View File
@@ -0,0 +1,32 @@
'use strict';
var nestedValue = require('../helpers/nestedValue');
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function groupBy(key) {
var _this = this;
var collection = {};
this.items.forEach(function (item, index) {
var resolvedKey = void 0;
if (isFunction(key)) {
resolvedKey = key(item, index);
} else if (nestedValue(item, key) || nestedValue(item, key) === 0) {
resolvedKey = nestedValue(item, key);
} else {
resolvedKey = '';
}
if (collection[resolvedKey] === undefined) {
collection[resolvedKey] = new _this.constructor([]);
}
collection[resolvedKey].push(item);
});
return new this.constructor(collection);
};
+17
View File
@@ -0,0 +1,17 @@
'use strict';
var variadic = require('../helpers/variadic');
module.exports = function has() {
var _this = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var properties = variadic(args);
return properties.filter(function (key) {
return Object.hasOwnProperty.call(_this.items, key);
}).length === properties.length;
};
+9
View File
@@ -0,0 +1,9 @@
'use strict';
module.exports = function implode(key, glue) {
if (glue === undefined) {
return this.items.join(key);
}
return new this.constructor(this.items).pluck(key).all().join(glue);
};
+15
View File
@@ -0,0 +1,15 @@
'use strict';
module.exports = function intersect(values) {
var intersectValues = values;
if (values instanceof this.constructor) {
intersectValues = values.all();
}
var collection = this.items.filter(function (item) {
return intersectValues.indexOf(item) !== -1;
});
return new this.constructor(collection);
};
+21
View File
@@ -0,0 +1,21 @@
'use strict';
module.exports = function intersectByKeys(values) {
var _this = this;
var intersectKeys = Object.keys(values);
if (values instanceof this.constructor) {
intersectKeys = Object.keys(values.all());
}
var collection = {};
Object.keys(this.items).forEach(function (key) {
if (intersectKeys.indexOf(key) !== -1) {
collection[key] = _this.items[key];
}
});
return new this.constructor(collection);
};
+9
View File
@@ -0,0 +1,9 @@
'use strict';
module.exports = function isEmpty() {
if (Array.isArray(this.items)) {
return !this.items.length;
}
return !Object.keys(this.items).length;
};
+5
View File
@@ -0,0 +1,5 @@
'use strict';
module.exports = function isNotEmpty() {
return !this.isEmpty();
};
+23
View File
@@ -0,0 +1,23 @@
'use strict';
module.exports = function join(glue, finalGlue) {
var collection = this.values();
if (finalGlue === undefined) {
return collection.implode(glue);
}
var count = collection.count();
if (count === 0) {
return '';
}
if (count === 1) {
return collection.last();
}
var finalItem = collection.pop();
return collection.implode(glue) + finalGlue + finalItem;
};
+24
View File
@@ -0,0 +1,24 @@
'use strict';
var nestedValue = require('../helpers/nestedValue');
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function keyBy(key) {
var collection = {};
if (isFunction(key)) {
this.items.forEach(function (item) {
collection[key(item)] = item;
});
} else {
this.items.forEach(function (item) {
var keyValue = nestedValue(item, key);
collection[keyValue || ''] = item;
});
}
return new this.constructor(collection);
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
module.exports = function keys() {
var collection = Object.keys(this.items);
if (Array.isArray(this.items)) {
collection = collection.map(Number);
}
return new this.constructor(collection);
};
+28
View File
@@ -0,0 +1,28 @@
'use strict';
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function last(fn, defaultValue) {
var items = this.items;
if (isFunction(fn)) {
items = this.filter(fn).all();
}
if (Array.isArray(items) && !items.length || !Object.keys(items).length) {
if (isFunction(defaultValue)) {
return defaultValue();
}
return defaultValue;
}
if (Array.isArray(items)) {
return items[items.length - 1];
}
var keys = Object.keys(items);
return items[keys[keys.length - 1]];
};
+5
View File
@@ -0,0 +1,5 @@
'use strict';
module.exports = function macro(name, fn) {
this.constructor.prototype[name] = fn;
};
+7
View File
@@ -0,0 +1,7 @@
'use strict';
module.exports = function make() {
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return new this.constructor(items);
};
+17
View File
@@ -0,0 +1,17 @@
'use strict';
module.exports = function map(fn) {
var _this = this;
if (Array.isArray(this.items)) {
return new this.constructor(this.items.map(fn));
}
var collection = {};
Object.keys(this.items).forEach(function (key) {
collection[key] = fn(_this.items[key], key);
});
return new this.constructor(collection);
};
+7
View File
@@ -0,0 +1,7 @@
'use strict';
module.exports = function mapInto(ClassName) {
return this.map(function (value, key) {
return new ClassName(value, key);
});
};
+9
View File
@@ -0,0 +1,9 @@
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
module.exports = function mapSpread(fn) {
return this.map(function (values, key) {
return fn.apply(undefined, _toConsumableArray(values).concat([key]));
});
};
+22
View File
@@ -0,0 +1,22 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
module.exports = function mapToDictionary(fn) {
var collection = {};
this.items.forEach(function (item, k) {
var _fn = fn(item, k),
_fn2 = _slicedToArray(_fn, 2),
key = _fn2[0],
value = _fn2[1];
if (collection[key] === undefined) {
collection[key] = [value];
} else {
collection[key].push(value);
}
});
return new this.constructor(collection);
};
+22
View File
@@ -0,0 +1,22 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
module.exports = function mapToGroups(fn) {
var collection = {};
this.items.forEach(function (item, key) {
var _fn = fn(item, key),
_fn2 = _slicedToArray(_fn, 2),
keyed = _fn2[0],
value = _fn2[1];
if (collection[keyed] === undefined) {
collection[keyed] = [value];
} else {
collection[keyed].push(value);
}
});
return new this.constructor(collection);
};
+31
View File
@@ -0,0 +1,31 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
module.exports = function mapWithKeys(fn) {
var _this = this;
var collection = {};
if (Array.isArray(this.items)) {
this.items.forEach(function (item, index) {
var _fn = fn(item, index),
_fn2 = _slicedToArray(_fn, 2),
keyed = _fn2[0],
value = _fn2[1];
collection[keyed] = value;
});
} else {
Object.keys(this.items).forEach(function (key) {
var _fn3 = fn(_this.items[key], key),
_fn4 = _slicedToArray(_fn3, 2),
keyed = _fn4[0],
value = _fn4[1];
collection[keyed] = value;
});
}
return new this.constructor(collection);
};
+17
View File
@@ -0,0 +1,17 @@
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
module.exports = function max(key) {
if (typeof key === 'string') {
var filtered = this.items.filter(function (item) {
return item[key] !== undefined;
});
return Math.max.apply(Math, _toConsumableArray(filtered.map(function (item) {
return item[key];
})));
}
return Math.max.apply(Math, _toConsumableArray(this.items));
};
+20
View File
@@ -0,0 +1,20 @@
'use strict';
module.exports = function median(key) {
var length = this.items.length;
if (key === undefined) {
if (length % 2 === 0) {
return (this.items[length / 2 - 1] + this.items[length / 2]) / 2;
}
return this.items[Math.floor(length / 2)];
}
if (length % 2 === 0) {
return (this.items[length / 2 - 1][key] + this.items[length / 2][key]) / 2;
}
return this.items[Math.floor(length / 2)][key];
};
+21
View File
@@ -0,0 +1,21 @@
'use strict';
module.exports = function merge(value) {
var arrayOrObject = value;
if (typeof arrayOrObject === 'string') {
arrayOrObject = [arrayOrObject];
}
if (Array.isArray(this.items) && Array.isArray(arrayOrObject)) {
return new this.constructor(this.items.concat(arrayOrObject));
}
var collection = JSON.parse(JSON.stringify(this.items));
Object.keys(arrayOrObject).forEach(function (key) {
collection[key] = arrayOrObject[key];
});
return new this.constructor(collection);
};
+39
View File
@@ -0,0 +1,39 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
module.exports = function mergeRecursive(items) {
var merge = function merge(target, source) {
var merged = {};
var mergedKeys = Object.keys(Object.assign({}, target, source));
mergedKeys.forEach(function (key) {
if (target[key] === undefined && source[key] !== undefined) {
merged[key] = source[key];
} else if (target[key] !== undefined && source[key] === undefined) {
merged[key] = target[key];
} else if (target[key] !== undefined && source[key] !== undefined) {
if (target[key] === source[key]) {
merged[key] = target[key];
} else if (!Array.isArray(target[key]) && _typeof(target[key]) === 'object' && !Array.isArray(source[key]) && _typeof(source[key]) === 'object') {
merged[key] = merge(target[key], source[key]);
} else {
merged[key] = [].concat(target[key], source[key]);
}
}
});
return merged;
};
if (!items) {
return this;
}
if (items.constructor.name === 'Collection') {
return new this.constructor(merge(this.items, items.all()));
}
return new this.constructor(merge(this.items, items));
};
+17
View File
@@ -0,0 +1,17 @@
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
module.exports = function min(key) {
if (key !== undefined) {
var filtered = this.items.filter(function (item) {
return item[key] !== undefined;
});
return Math.min.apply(Math, _toConsumableArray(filtered.map(function (item) {
return item[key];
})));
}
return Math.min.apply(Math, _toConsumableArray(this.items));
};
+42
View File
@@ -0,0 +1,42 @@
'use strict';
module.exports = function mode(key) {
var values = [];
var highestCount = 1;
if (!this.items.length) {
return null;
}
this.items.forEach(function (item) {
var tempValues = values.filter(function (value) {
if (key !== undefined) {
return value.key === item[key];
}
return value.key === item;
});
if (!tempValues.length) {
if (key !== undefined) {
values.push({ key: item[key], count: 1 });
} else {
values.push({ key: item, count: 1 });
}
} else {
tempValues[0].count += 1;
var count = tempValues[0].count;
if (count > highestCount) {
highestCount = count;
}
}
});
return values.filter(function (value) {
return value.count === highestCount;
}).map(function (value) {
return value.key;
});
};
+15
View File
@@ -0,0 +1,15 @@
'use strict';
var values = require('../helpers/values');
module.exports = function nth(n) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var items = values(this.items);
var collection = items.slice(offset).filter(function (item, index) {
return index % n === 0;
});
return new this.constructor(collection);
};
+31
View File
@@ -0,0 +1,31 @@
'use strict';
var variadic = require('../helpers/variadic');
module.exports = function only() {
var _this = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var properties = variadic(args);
if (Array.isArray(this.items)) {
var _collection = this.items.filter(function (item) {
return properties.indexOf(item) !== -1;
});
return new this.constructor(_collection);
}
var collection = {};
Object.keys(this.items).forEach(function (prop) {
if (properties.indexOf(prop) !== -1) {
collection[prop] = _this.items[prop];
}
});
return new this.constructor(collection);
};
+35
View File
@@ -0,0 +1,35 @@
'use strict';
var clone = require('../helpers/clone');
module.exports = function pad(size, value) {
var abs = Math.abs(size);
var count = this.count();
if (abs <= count) {
return this;
}
var diff = abs - count;
var items = clone(this.items);
var isArray = Array.isArray(this.items);
var prepend = size < 0;
for (var iterator = 0; iterator < diff;) {
if (!isArray) {
if (items[iterator] !== undefined) {
diff += 1;
} else {
items[iterator] = value;
}
} else if (prepend) {
items.unshift(value);
} else {
items.push(value);
}
iterator += 1;
}
return new this.constructor(items);
};
+33
View File
@@ -0,0 +1,33 @@
'use strict';
module.exports = function partition(fn) {
var _this = this;
var arrays = void 0;
if (Array.isArray(this.items)) {
arrays = [new this.constructor([]), new this.constructor([])];
this.items.forEach(function (item) {
if (fn(item) === true) {
arrays[0].push(item);
} else {
arrays[1].push(item);
}
});
} else {
arrays = [new this.constructor({}), new this.constructor({})];
Object.keys(this.items).forEach(function (prop) {
var value = _this.items[prop];
if (fn(value) === true) {
arrays[0].put(prop, value);
} else {
arrays[1].put(prop, value);
}
});
}
return new this.constructor(arrays);
};
+5
View File
@@ -0,0 +1,5 @@
'use strict';
module.exports = function pipe(fn) {
return fn(this);
};
+106
View File
@@ -0,0 +1,106 @@
'use strict';
var _require = require('../helpers/is'),
isArray = _require.isArray,
isObject = _require.isObject;
var nestedValue = require('../helpers/nestedValue');
var buildKeyPathMap = function buildKeyPathMap(items) {
var keyPaths = {};
items.forEach(function (item, index) {
function buildKeyPath(val, keyPath) {
if (isObject(val)) {
Object.keys(val).forEach(function (prop) {
buildKeyPath(val[prop], keyPath + '.' + prop);
});
} else if (isArray(val)) {
val.forEach(function (v, i) {
buildKeyPath(v, keyPath + '.' + i);
});
}
keyPaths[keyPath] = val;
}
buildKeyPath(item, index);
});
return keyPaths;
};
module.exports = function pluck(value, key) {
if (value.indexOf('*') !== -1) {
var keyPathMap = buildKeyPathMap(this.items);
var keyMatches = [];
if (key !== undefined) {
var keyRegex = new RegExp('0.' + key, 'g');
var keyNumberOfLevels = ('0.' + key).split('.').length;
Object.keys(keyPathMap).forEach(function (k) {
var matchingKey = k.match(keyRegex);
if (matchingKey) {
var match = matchingKey[0];
if (match.split('.').length === keyNumberOfLevels) {
keyMatches.push(keyPathMap[match]);
}
}
});
}
var valueMatches = [];
var valueRegex = new RegExp('0.' + value, 'g');
var valueNumberOfLevels = ('0.' + value).split('.').length;
Object.keys(keyPathMap).forEach(function (k) {
var matchingValue = k.match(valueRegex);
if (matchingValue) {
var match = matchingValue[0];
if (match.split('.').length === valueNumberOfLevels) {
valueMatches.push(keyPathMap[match]);
}
}
});
if (key !== undefined) {
var collection = {};
this.items.forEach(function (item, index) {
collection[keyMatches[index] || ''] = valueMatches;
});
return new this.constructor(collection);
}
return new this.constructor([valueMatches]);
}
if (key !== undefined) {
var _collection = {};
this.items.forEach(function (item) {
if (nestedValue(item, value) !== undefined) {
_collection[item[key] || ''] = nestedValue(item, value);
} else {
_collection[item[key] || ''] = null;
}
});
return new this.constructor(_collection);
}
return this.map(function (item) {
if (nestedValue(item, value) !== undefined) {
return nestedValue(item, value);
}
return null;
});
};
+52
View File
@@ -0,0 +1,52 @@
'use strict';
var _require = require('../helpers/is'),
isArray = _require.isArray,
isObject = _require.isObject;
var deleteKeys = require('../helpers/deleteKeys');
module.exports = function pop() {
var _this = this;
var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
if (this.isEmpty()) {
return null;
}
if (isArray(this.items)) {
if (count === 1) {
return this.items.pop();
}
return new this.constructor(this.items.splice(-count));
}
if (isObject(this.items)) {
var keys = Object.keys(this.items);
if (count === 1) {
var key = keys[keys.length - 1];
var last = this.items[key];
deleteKeys(this.items, key);
return last;
}
var poppedKeys = keys.slice(-count);
var newObject = poppedKeys.reduce(function (acc, current) {
acc[current] = _this.items[current];
return acc;
}, {});
deleteKeys(this.items, poppedKeys);
return new this.constructor(newObject);
}
return null;
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
module.exports = function prepend(value, key) {
if (key !== undefined) {
return this.put(key, value);
}
this.items.unshift(value);
return this;
};
+20
View File
@@ -0,0 +1,20 @@
'use strict';
var _require = require('../helpers/is'),
isFunction = _require.isFunction;
module.exports = function pull(key, defaultValue) {
var returnValue = this.items[key] || null;
if (!returnValue && defaultValue !== undefined) {
if (isFunction(defaultValue)) {
returnValue = defaultValue();
} else {
returnValue = defaultValue;
}
}
delete this.items[key];
return returnValue;
};
+9
View File
@@ -0,0 +1,9 @@
'use strict';
module.exports = function push() {
var _items;
(_items = this.items).push.apply(_items, arguments);
return this;
};
+7
View File
@@ -0,0 +1,7 @@
'use strict';
module.exports = function put(key, value) {
this.items[key] = value;
return this;
};
+18
View File
@@ -0,0 +1,18 @@
'use strict';
var values = require('../helpers/values');
module.exports = function random() {
var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var items = values(this.items);
var collection = new this.constructor(items).shuffle();
// If not a length was specified
if (length !== parseInt(length, 10)) {
return collection.first();
}
return collection.take(length);
};
+23
View File
@@ -0,0 +1,23 @@
'use strict';
module.exports = function reduce(fn, carry) {
var _this = this;
var reduceCarry = null;
if (carry !== undefined) {
reduceCarry = carry;
}
if (Array.isArray(this.items)) {
this.items.forEach(function (item) {
reduceCarry = fn(reduceCarry, item);
});
} else {
Object.keys(this.items).forEach(function (key) {
reduceCarry = fn(reduceCarry, _this.items[key], key);
});
}
return reduceCarry;
};
+7
View File
@@ -0,0 +1,7 @@
'use strict';
module.exports = function reject(fn) {
return new this.constructor(this.items).filter(function (item) {
return !fn(item);
});
};
+25
View File
@@ -0,0 +1,25 @@
'use strict';
module.exports = function replace(items) {
if (!items) {
return this;
}
if (Array.isArray(items)) {
var _replaced = this.items.map(function (value, index) {
return items[index] || value;
});
return new this.constructor(_replaced);
}
if (items.constructor.name === 'Collection') {
var _replaced2 = Object.assign({}, this.items, items.all());
return new this.constructor(_replaced2);
}
var replaced = Object.assign({}, this.items, items);
return new this.constructor(replaced);
};
+51
View File
@@ -0,0 +1,51 @@
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
module.exports = function replaceRecursive(items) {
var replace = function replace(target, source) {
var replaced = Object.assign({}, target);
var mergedKeys = Object.keys(Object.assign({}, target, source));
mergedKeys.forEach(function (key) {
if (!Array.isArray(source[key]) && _typeof(source[key]) === 'object') {
replaced[key] = replace(target[key], source[key]);
} else if (target[key] === undefined && source[key] !== undefined) {
if (_typeof(target[key]) === 'object') {
replaced[key] = Object.assign({}, source[key]);
} else {
replaced[key] = source[key];
}
} else if (target[key] !== undefined && source[key] === undefined) {
if (_typeof(target[key]) === 'object') {
replaced[key] = Object.assign({}, target[key]);
} else {
replaced[key] = target[key];
}
} else if (target[key] !== undefined && source[key] !== undefined) {
if (_typeof(source[key]) === 'object') {
replaced[key] = Object.assign({}, source[key]);
} else {
replaced[key] = source[key];
}
}
});
return replaced;
};
if (!items) {
return this;
}
if (!Array.isArray(items) && (typeof items === 'undefined' ? 'undefined' : _typeof(items)) !== 'object') {
return new this.constructor(replace(this.items, [items]));
}
if (items.constructor.name === 'Collection') {
return new this.constructor(replace(this.items, items.all()));
}
return new this.constructor(replace(this.items, items));
};
+7
View File
@@ -0,0 +1,7 @@
'use strict';
module.exports = function reverse() {
var collection = [].concat(this.items).reverse();
return new this.constructor(collection);
};
+40
View File
@@ -0,0 +1,40 @@
'use strict';
/* eslint-disable eqeqeq */
var _require = require('../helpers/is'),
isArray = _require.isArray,
isObject = _require.isObject,
isFunction = _require.isFunction;
module.exports = function search(valueOrFunction, strict) {
var _this = this;
var result = void 0;
var find = function find(item, key) {
if (isFunction(valueOrFunction)) {
return valueOrFunction(_this.items[key], key);
}
if (strict) {
return _this.items[key] === valueOrFunction;
}
return _this.items[key] == valueOrFunction;
};
if (isArray(this.items)) {
result = this.items.findIndex(find);
} else if (isObject(this.items)) {
result = Object.keys(this.items).find(function (key) {
return find(_this.items[key], key);
});
}
if (result === undefined || result < 0) {
return false;
}
return result;
};

Some files were not shown because too many files have changed in this diff Show More