labs42io / itiriri

A library built for ES6 iteration protocol.

Home Page:https://labs42io.github.io/itiriri

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Export the Itiriri class

tobia opened this issue · comments

commented

If you don't mind me asking, why is the main Itiriri class not exported? It would make it easier to extend it and add more methods.

As it stands, one is left with two options, both sub-optimal:

  • copy the entire source of the Itiriri class, just to add a couple metods
  • fiddle with prototypes at runtime

Right now I'm going with option 2:

import itiriri, { IterableQuery } from 'itiriri'
import equal from '@wry/equality'

// extend the IterableQuery interface for the type checker
declare module 'itiriri' {
  export interface IterableQuery<T> {
    /**
     * Returns `true` if this sequence is equal to the given sequence.
     */
    equals(other: Iterable<T>): boolean
  }
}

// export a function with a new name so that the IDE knows to import from here
export default function from<T>(source: Iterable<T>): IterableQuery<T> {
  return itiriri(source)
}

// HACK: obtain a reference to the Itiriri class from an instance
const Itiriri = itiriri([]).constructor

// implement the extensions
Itiriri.prototype.equals = function <T>(other: Iterable<T>): boolean {
  const as = this[Symbol.iterator]()
  const bs = other[Symbol.iterator]()
  while (true) {
    const a = as.next()
    const b = bs.next()
    if (a.done && b.done) return true
    if (a.done !== b.done || !equal(a.value, b.value)) return false
  }
}

Client code:

import from from '../lib/from'

// ...
  from(someArray)
    .map((it) => it.value)
    .take(somePrefix.length)
    .equals(somePrefix)
// ...