Google News
logo
Collect.js - Interview Questions
What about last(), macro() and make() methods in Collect.js?
last() : The last() method returns the last element in the collection that passes a given truth test:
const collection = collect([1, 2, 3]);

const last = collection.last(item => item > 1);

// 3
You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:
collect([1, 2, 3, 4]).last();

// 4
macro() : The macro() method lets you register custom methods
collect().macro('uppercase', function () {
  return this.map(item => item.toUpperCase());
});

const collection = collect(['a', 'b', 'c']);

collection.uppercase();

collection.all();

// ['A', 'B', 'C']
Note that the macro method returns undefined, and therefore it is not possible to use it within a chain of methods.
 
make() : The make() method creates a new collection instance.
 
This is only added to adhere to the Laravel collection API, when using Collect.js it's recommended to use collect() directly when creating a new collection.
Advertisement