Skip to content

Suggestions/questions #19

@OliverJAsh

Description

@OliverJAsh

Hi! Firstly, thanks for the great project. This is exactly what I've been looking for. I want to ask a few questions and raise a few ideas, if you have the time!

  1. It would be really convenient to have type-specific convenience methods like mapValues/toMap for Map.
  2. I've started writing some type definitions in TypeScript. Perhaps we could add these to the project? You could continue to ship the compiled JS, plus we and any other TypeScript users of this library get type safety!

Here's an extract of what I've been working on for the above two suggestions. Let me know what you think and whether this is worth taking any further!

class Functified<A> {
    constructor(
        public iterable: Iterable<A>
    ) {}

    *[Symbol.iterator]() {
        for (const value of this.iterable) {
            yield value;
        }
    }

    map<B>(fn: (t: A) => B) {
        const { iterable } = this;
        const generator = function* () {
            for (const value of iterable) {
                yield fn(value);
            }
        };
        return Functified.fromGenerator(generator);
    }

    static fromGenerator<B>(generator: () => IterableIterator<B>) {
        const iterable: Iterable<B> = {
            [Symbol.iterator]: generator
        };
        return new Functified(iterable);
    }
}

class FunctifiedMap<K, V> extends Functified<[K, V]> {
    constructor(map: Iterable<[K, V]>) {
        super(map)
    }

    mapValues<V2>(fn: (t: V) => V2) {
        return new FunctifiedMap(
            this.map(([ key, value ]): [ K, V2 ] => [ key, fn(value) ])
        )
    }

    toMap() {
        const transformedArray = Array.from(this.iterable);
        return new Map(transformedArray);
    }

    static fromGenerator<K, V>(generator: () => IterableIterator<[K, V]>) {
        const iterable: Iterable<[K, V]> = {
            [Symbol.iterator]: generator
        };
        return new FunctifiedMap(iterable);
    }
}

{
    const originalMap = new Map([ [ 'x', 5 ], [ 'y', 10 ] ]);

    const transformedMapAsFunctifiedMap = new FunctifiedMap(originalMap)
        .mapValues(value => value * 5)

    console.log(transformedMapAsFunctifiedMap.toMap())
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions