Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Export the Itiriri class #8

Open
tobia opened this issue Jul 1, 2021 · 0 comments
Open

Export the Itiriri class #8

tobia opened this issue Jul 1, 2021 · 0 comments

Comments

@tobia
Copy link

tobia commented Jul 1, 2021

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)
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant