This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Create a Sequence Helper to Transduce Without Changing Collection Types

    Paul FrendPaul Frend

    A frequent use case when transducing is to apply a transformation to items without changing the type of the collection.

    In this lesson, we'll create a helper to do just that. seq will be similar to into, except the target type will be inferred from the source collection. For example, if transducing from an array, seq will create an array as the output collection as well.

    seq is thus more restrictive and easier to consume than into.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Let's create a function Seq, short for sequence, which will call transduce under the hood. The difference to our Into helper is that Seq is going to infer the destination collection based on the type of the source collection. Seq is more constrained than Into, but useful when you know you don't want to change collection types.

    00:19 As their arguments then, all we need is a transform and a collection. I'm just going to copy the body from Into, and paste it in. The only change we need to make is remove the 2 two argument with an empty collection of the right type. For an array, this will be an empty array. Here, it'll be an empty object. Let's just make our error message a bit more generic.

    00:45 Let's try this out by doubling an array. We'll call Seq, and our transform will be a map that doubles values, and we need a source array with a few numbers. Let's try it out. We get an error, so it looks like we're still checking the 2 argument up here, whereas, really, we should be checking our collection. Let's fix that. Now ,we get our expected result.

    01:12 Let's also try this out with an object. For that, we'll create a transform called Flip, and it's going to flip the keys and the values. We'll call map, destructure the key and the value from our array, we'll need another bracket here, and we'll just return those two, flipped like so. We can call Seq with flip, and we'll pass in a plain object with three pairs.

    01:41 As expected, our returned object has the keys and the values flipped.

    Discuss

    Discuss