ecrmnn / collect.js

💎  Convenient and dependency free wrapper for working with arrays and objects
https://collect.js.org
MIT License
6.54k stars 313 forks source link

Add `firstOr` method #279

Closed stevebauman closed 2 years ago

stevebauman commented 2 years ago

Description

This PR introduces the firstOr() method, which simplifies first() calls so you no longer have to pass in null as the first parameter.

Examples

Before:

collect().first(null, 'default')

// default

After:

collect().firstOr('default');

// default

With callback:

collect([1, 2, 3, 4])
    .where(value => value === 5)
    .firstOr(() => {
        throw new Error('Item not found.');
    });

// Throws error.

No hard feelings on closure. I love this library and I really appreciate your hard work on this ❤️


Maybe we could also introduce a firstOrFail() as well that would throw an error when an item isn't found? What are your thoughts/opinion on this? I can submit a PR if you give the go ahead 👍

// firstOrFail.js

module.exports = function () {
    return this.firstOr(() => {
        throw new Error('Item not found.');
    });
};

// Usage

collect().firstOrFail();
ecrmnn commented 2 years ago

Hi, @stevebauman.

Thanks for a solid PR! Unfortunately firstOr isn't part of Laravel Collections API, it's only available in Eloquent.

Therefore, merging this would break the adherence to the Laravel Collection API.

If you want another challenge, the sole and firstOrFail methods need to be implemented.

stevebauman commented 2 years ago

Ok! No worries 😄 , I'll PR the firstOrFail method 👍