Google News
logo
Collect.js - Interview Questions
Explain take(), takeUntil() and takeWhile() methods in Collect.js?
take() : The take() method returns a new collection with the specified number of items: You may also pass a negative integer to take the specified amount of items from the end of the collection:
const collection = collect([0, 1, 2, 3, 4, 5]);

const chunk = collection.take(3);

chunk.all();

// [0, 1, 2]
 
takeUntil() : The takeUntil() method returns items in the collection until the given callback returns true:
const collection = collect([1, 2, 3, 4]);

const subset = collection.takeUntil(item => item >= 3);

subset.all();

// [1, 2]
If the given value is not found or the callback never returns true, the takeUntil method will return all items in the collection.
 
You may also pass a simple value to the takeUntil() method to get the items until the given value is found:
const collection = collect([1, 2, 3, 4]);

const subset = collection.takeUntil(3);

subset.all();

// [1, 2]
takeWhile() : The takeWhile() method returns items in the collection until the given callback returns false:
const collection = collect([1, 2, 3, 4]);

const subset = collection.takeWhile(item => item < 3);

subset.all();

// [1, 2]
If the callback never returns false, the takeWhile method will return all items in the collection.
Advertisement