Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create a Sequence Helper to Transduce Without Changing Collection Types


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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.

    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.

    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.

    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.

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