Giter Club home page Giter Club logo

collect.js's People

Contributors

ajaymathur avatar anupvarghese avatar brainmaestro avatar dalook avatar dducro avatar dogoku avatar dsymonov-jc avatar ecrmnn avatar ennetech avatar g-plane avatar helfull avatar jbtbnl avatar jeromedeleon avatar lucacri avatar maicol07 avatar marcus-at-localhost avatar matrunchyk avatar mattstypa avatar nhat-phan avatar okonomiyaki3000 avatar pf-jordy avatar philippkuehn avatar s-patompong avatar sacharbit avatar slowvoid avatar stevebauman avatar tenghuanhe avatar v-stein avatar wangzhenhui1992 avatar zpwparsons avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

collect.js's Issues

where(' ' ,'like', ' ') like operator

This is awesome collection as like laravel .
like operator is very important as query system.
.where('name','like','s%')
another is
.orWhere()

.where('votes', '>', 100)
.orWhere('name', 'John')

andWhere() array condition

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();

without those can't feel happiness .please add those collections. @ecrmnn ❤️

Cast object to array

Would it be possible to auto-cast the collection to an array like Laravel does when PHP expects an array? For example this isn't possible right now:

const collection = collect([1,2,3,4,5]);

for (let item of collection) {
    // Do something with item
}

Firefox SyntaxError: missing = in const declaration

i'm getting this error on firefox

SyntaxError: missing = in const declaration

module.exports = function except(properties) {
const collection = {};

for (const prop in this.items) {
if (properties.indexOf(prop) === -1) {
collection[prop] = this.items[prop];
}
}

return new this.constructor(collection);
};

The only() method with array It does not work properly

const collection = collect([{
  name: 'JavaScript: The Good Parts', pages: 176
}, {
  name: 'JavaScript: The Definitive Guide', pages: 1096
}]);

return collection.only('name').all()

I'm trying to find a 'name' property from the collection. It does not work properly. It displays empty arrays [] I want to know my approach is correct or not.

Thank you.

toArray - cannot reproduce the following Laravel Collection behavior

$collection = new Collection([
		['shape' => 'square', 'color' => 'blue', 'val' => 'blue square'],
		['shape' => 'square', 'color' => 'blue', 'val' => 'blue square'],
		['shape' => 'triangle', 'color' => 'green', 'val' => 'green triangle'],
		['shape' => 'triangle', 'color' => 'red', 'val' => 'red triangle'],
]);

$result = $collection->groupBy('shape')->map(
	function(Collection $dimension1Group) {
		return $dimension1Group->groupBy('color');
	}
)->toArray();

//array (
//	'square' =>
//		array (
//			'blue' =>
//				array (
//					0 =>
//						array (
//							'shape' => 'square',
//							'color' => 'blue',
//							'val' => 'blue square',
//						),
//					1 =>
//						array (
//							'shape' => 'square',
//							'color' => 'blue',
//							'val' => 'blue square',
//						),
//				),
//		),
//	'triangle' =>
//		array (
//			'green' =>
//				array (
//					0 =>
//						array (
//							'shape' => 'triangle',
//							'color' => 'green',
//							'val' => 'green triangle',
//						),
//				),
//			'red' =>
//				array (
//					0 =>
//						array (
//							'shape' => 'triangle',
//							'color' => 'red',
//							'val' => 'red triangle',
//						),
//				),
//		),
//)

I'd like to address two things with this example:

  • The collect().toArray function does not support iteration over nested collections when the topmost collection is a key-value map (javascript object).
  • We lose the keys when using collect().toArray as opposed to Laravel Collection. In case this is the expected behavior (after all Javascript != PHP), it would be helpful to specify this deviation in the README.

Contains on collection of objects

The contains function isn't working properly on collections of objects.

Example:

let collection = collect([{
  name: 'Steven Gerrard',
  number: 8
}, {
  name: 'Steve Jobs',
  number: 2
}]);

let result = collection.contains('name', 'Steven Gerrard'); // false
// Expected result: true

For people having the same issue, you can currently use the following as a workaround:

collection.where('name', 'Tony Stark').first() === undefined;

count() does not work with hashmaps

hey,

counting objects in a hashmap returns undefined

collect({}).count() // undefined
collect({foo:'bar'}).count() // undefined

might just be a version problem here

Splitting functions into separate files

Due to the number of implemented functions, the code starts getting a little difficult to parse. Would you be interested in splitting the functions into separate files? It's not necessary, but I feel like it would help encourage contribution.

Great project btw.

bug in merge&union method?

`const collection = collect({
a: 'A',
b: 'B',
d: 'D'
});

const merged = collection.merge({
a: 'AAA',
b: 'BBB',
c: 'CCC'
});

console.log(merged.all()) // { a: 'AAA', b: 'BBB', c: 'CCC' } but expect { a: 'AAA', b: 'BBB', c: 'CCC' , d: 'D'}

console.log(merged.all().b) // BBB
merged.forget('b')
console.log(merged.all().b) // B, expect undefined
i know in method file: merge.js and union.js usevar collection = Object.create(this.items), does use clone` like is right/better?

env: node -v v6.10.2

Doesn't work with vuejs v-for

First thanks for this package, it's like using laravel collections.

I tried to use one of your collections in a v-for in vue and it doesn't iterate over the collection items, instead it iterates over the collection Object properties.

I have the latest version of your package.

how about adding a CONTRIBUTING.md?

Hey,

could you write a short CONTRIBUTING.md, so everyone who wants to constribute knows how.

i myself would like to constribute but i cant get the env working to run those tests.

mapWithKeys after groupBy errors with "this.items.forEach is not a function"

hey,

i have this pipeline

const stats = collect(this.content)
                    .filter(value => {
                        return collect([
                            'created', 'updated', 'deleted'
                        ]).contains(value.description);
                    })
                    .groupBy(value => value.description)
                    .mapWithKeys(value => {
                        return [value.description, collect(value.all()).count()];
                    });

and this does error with this.items.forEach is not a function at the mapWithKeys method,

is it intentional that mapWithKeys does not support hashmaps?

Sum using iterator/reduce

I've opened PR#95 several days ago, which uses reduce instead of iterator to implement sum function with fewer lines of code. However, a simple benchmark test shows iterator_sum is 3x ~ 5x times faster than reduce_sum.

According to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce, reduce does have extra overhead compared to directly using iterator.

So the change of PR#95 may be revoked and using origin sum implementation is better. Using reduce makes the code shorter, it harms efficiency. How do you think about it? @ecrmnn

FlatMap functionality is not as expected

The flatMap method doesn't work as expected for a collection (an array of objects).
For example, if I have a list of employees and each employee has a list of customers and I want to get a list of all customer I would use flatMap as the below:
Input:

let employees = collect([
  {
    customers :[
      {
        name : "c1"
      },
      {
        name : "c2"
      }
    ]
  },
  {
    customers :[
      {
        name : "c3"
      }
    ]
  }
])

let customers = employees.flatMap(employee => employee.customers)

Expected result:

[
  {
    name : "c1"
  },
  {
    name : "c2"
  },
  {
    name : "c3"
  }
]

Actual result:
Error: Cannot read property '0' of undefined(in the collect.js flatMap source code)

Laravel's flatMap source code

Is there a good reason why flatMap behaves like that? If it is an issue with this can you, please, implement the correct version for flatMap?

Thank you!

Merge() not working as expected ?

Hey,

I'm noticing an issue with the merge() method. Here's what I'm getting running the example:

const collection = collect({
	id: 1,
	price: 29
});

const merged = collection.merge({
	price: 400,
	discount: false
});

console.log(merged.all());

In my console:

img

So, I don't have a complete understanding of JS prototypes, but from what I can see the object returned only has the content of the merged object (the second object), and it's prototype has the original data (the first object).

Am I not getting something or is this unexpected behavior ?

Thanks !

random() mutates the collection

The random method returns a random item from the collection:

Not only that, it shuffles the collection in place:

const a = collect([1, 2, 3, 4, 5])

console.log(a.random())    // 4
console.log(a.all())       // [3, 5, 1, 4, 2]

I humbly suggest it would be more clear to either update the documentation to note that, or to adjust the code to be pure -- a user might not expect their ordered array to be shuffled when asking for a random element.

How to use without npm?

Hello

Is it possible to use this package without npm?

I was expecting to see a collect.js or a collect.min.js in the dist folder.

pull leaving behind undefined objects in collection

const testCollection = collect(["test-1", "test-2", "test-3", "test-4", "test-5"]);

const test1 = testCollection.pull(0);
console.log(test1);
console.log(testCollection.count());

const test2 = testCollection.pull(1);
console.log(test2);
console.log(testCollection.count());

testCollection.push("test-6");
console.log(testCollection.count());

testCollection.push("test-7");
console.log(testCollection.count());

console.log(testCollection.all());

Results:
image

Sorting strings with accented characters

Knows how to order an array with words with special characters like accents?

Javascript has a native method sort that allows sorting ( array.sort() ). Also you can provide your own custom sorting function. Are two ways to overcome this behavior localeCompare and Intl.Collator provided. in .sortBy() could have this option.

collect(array).sortBy('name');

returns 'Albacete' before 'Álava', and I want 'Álava' before 'Albacete'. =(

Thanks a lot, @ecrmnn

Most methods only work if underlying data is an array

Most methods (like "where") only work on array data.

Take this as an example:

let filtered = collect([
    { test: 1 },
    { test: 2 }
]).where('test', 2);

filtered equals a collection with just the second object.
However the following throws an exception.

let filtered = collect([
    { test: 1 },
    { test: 2 }
]).keyBy('test').where('test', 2);

This is because by calling keyBy() the underlying array is converted to an object.

I understand this is done, however I also expect methods like where() are still usable.

Is it an option to convert the items property to an array (if it is an object) in the affected methods to preserve expected behavior?
Beside this keys also need the be preserved, so just converting it to an array is not a complete solution..

how to use it in plain javascript ?

Hi i want to use this library in plain javascript like we use Jquery.

this is very good library and i want to use this in my html file.
please guide how to use this.

except on arrays

Problem:
except doesn't work on arrays, but intersect does? Is this inconsistent or correct behavior?

const testE = collect([1,2,3,4,5]).except([2,12]).all()
// result is an object: ​​​​​{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }​​​​​
// think i wanted array: [12]

const testI = collect([1, 2, 3, 4, 5]).intersect([1, 2, 3, 9]).all();
// result: [1,2,3]

except returns object, intersect returns array.

in sql world:
http://www.essentialsql.com/wp-content/uploads/2014/10/UnionInsersectExcept.jpg

thanks :-)

Ps. Love this awesome framework ;-)

.all, toArray, toJSON not returning expected results

If I use those three methods(.all, toArray, toJSON) on a collection with sub-collections I get the items property from children in the result.

It shouldn't recursively get the items for each collection?

Why I have sub-collections? Because I want, at some point, to process only the data from children and I don't want to create temporary variables and instantiate a new collection().

Suggestion: Offer the not implemented methods as aliases?

I was looking at the few methods that are not implemented, but which are in Laravel, and was wondering if it might be a good idea to implemented them as aliases/wrappers that just call the intended method? This would keep users from having to worry about differences to Laravel, since overall it is expected to be the same (noting that this collection manager is always strict).

Adding dump command?

In light of the pending Laravel 5.5 release, so you have any plans for add dump and/or dd commands?

Unable to run npm run production in laravel 5.4

I'm importing collect globally in laravel's default bootstrap.js file:

window.collect = require('collect.js');

When I run npm run development everything works fine.

When I run npm run production I get the following error:

> @ production C:\www\kilt2016
> cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

 95% emitting ERROR  Failed to compile with 1 errors7:21:22 PM

 error

/js/oa/vue.57617082aa194c799028.js from UglifyJs
Unexpected token: name (index) [./~/collect.js/src/methods/chunk.js:5,0][/js/oa/vue.57617082aa194c799028.js:79,6]

(Laravel version: 5.4.24, Mix Version: 0.12.1)

Anyone any ideas?

Doesn't work well in IE

I get a const is not initialized. It points to this function, but I guess it's valid for all. Would it be possible to make it available for IE too?

Collection.prototype.only = function (properties) {
  const collection = {};

  for (const prop in this.items) {
    if (properties.indexOf(prop) !== -1) {
      collection[prop] = this.items[prop];
    }
  }

  return new Collection(collection);
};

How to access value by index ID in array ?

*Library is missing Value By Index Functionality

ex

myArray = collect([1,4,5,9,9,5,1,1,5,4,1,7,1,0,9,3,7,4,8,9,3,6,3,3]);

val = myArray[3];

it is not returning value .

it should return value 9

ReferenceError: collect is not defined

Hi

I am using Laravel 5.5;

I have installed using npm

npm install --save collect.js

and added the following on bootstrap.js

window.collect = require('collect.js')

and run
npm run dev

inside my blade blade file i have added

<script>
collect([1, 2, 3]).all();
</script>

But I am getting an error

ReferenceError: collect is not defined

`macro` method is only callable on an instance

Hey,

if i want to create a macro for global use, like in laravel. I would do something like this:

collect.marco('hello', function(fn) {
  console.log('hello');
});

and then use it were ever i need it.
but with the current implementation i get the error:

collect.macro is not a function

Working with objects

Just checking about the "wrapper for working with arrays and objects". Is this implemented yet? It's just when I pass in an object and try and use many of the functions: transform, map, pop etc. then it fails as it is trying to call the corresponding methods on this.items assuming that it is an array.

Am I doing something wrong or can I just not use objects in collect.js?

Brilliant library otherwise 👍

What does it should be when we call `toArray()`?

Suppose there is an object collection like that

people = {
  name: 'wei',
  sex: 'male',
  phone: [15211111111, 13511111111],
  company: {
    name: 'IBM',
    city: 'BJ'
  }
}

What does it should be if we call collect(people).toArray()?
In current implementation, it will return
[ 'wei', 'male', [ 15211111111, 13511111111 ], { name: 'IBM', city: 'BJ' } ].
Should it be [ 'wei', 'male', [ 15211111111, 13511111111 ], [ 'IBM', 'BJ' ] ]?

can't setup collect.js in vue js

NB: SOLVED

<template lang="html">
  <div class="app">
    {{ test}}
  </div>
</template>

<script>

import collect from  'collect.js'

export default {
data () {
  return {
    msg: 'Atom_Vue',
    test: ' '
  }
},
created() {
    this.test = collect([1, 2, 3, 4]).count()
  },
}
</script>

<style lang="css" scoped >

</style>

output issue :

Error in render: "TypeError: [1,2,3,4].count is not a function"

it is possible to get collection async?

i want something like

const collect = require('collect.js')

collect(['a', 'b', 'c'])
    .toArray(array => /** do something */)

it is possible to achieve with current version?

Regression stats / benchmark

Thanks for your work on this. Do you have any stats on upper limits with larger collection sizes, benchmarked performances etc?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.