Lazy zipping

The zipping methods that we've looked at so far have all been called on lists. If you want to lazily zip lists together, you have to use a sequence, as follows:

names
.toSeq()
.zipWith(
(...maps) => Map().merge(...maps),
roles,
ages
)
.forEach(v => console.log('lazy zipWith', v.toJS()));
// -> lazy zipWith { name: 'Jeremy', role: 'Engineer', age: 34 }
// -> lazy zipWith { name: 'Garry', role: 'Designer', age: 23 }
// -> lazy zipWith { name: 'Katie', role: 'Programmer', age: 36 }

You don't have to convert each of your lists to sequences in order to lazy zip them together. By calling toSeq() on the names list just before calling zipWith(), you're zipping together one map at a time as it's fed into the forEach() side-effect. Now that we're using a sequence for lazy zipping, let's look at another approach:

names
.toSeq()
.zip(roles, ages)
.map(maps => Map().merge(...maps))
.forEach(v => console.log('lazy zip', v.toJS()));
// -> lazy zip { name: 'Jeremy', role: 'Engineer', age: 34 }
// -> lazy zip { name: 'Garry', role: 'Designer', age: 23 }
// -> lazy zip { name: 'Katie', role: 'Programmer', age: 36 }

Instead of using zipWith() we'll be using zip(), which results in an array of maps being passed to the next method. Then, we use map() to perform our merge. This approach is very similar to zipWith()—since we're now using a sequence to execute things lazily, there's no harm in putting our map merging logic into a separate map() call. Remember, sequences don't create new collections in between chained method calls.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.255.127