Skip to content

Wraps any JavaScript iterable to provide a common set of chainable methods

License

Notifications You must be signed in to change notification settings

jmakeig/iterant

Repository files navigation

A wrapper type that abstracts lazy and eager iterables and provides chaining methods, similar to Array.prototype.

Usage

Iterant

Wraps any JavaScript iterable (i.e. an object that has a Symbol.iterator property) to provide a common iterface, regardless of the underlying concrete type. Where possible and apporpriate this interface matches the built-in Array. Thus, you can call the same Iterant#map on an Array, a MarkLogic Seqeunce, or a generator—anything that’s iterable. Type-specific Iterant extensions override the built-in methods to provide implementations that delegate to their wrapped concrete types.

Parameters

  • iterable Iterable Any iterable (i.e. something that has a Symbol.iterator property)

Examples

Iterant(
  cts.collections() // Any iterable, such as Array, Map, generator function, etc.
)
  .filter(c => true) // Not very discriminating
  .map(c => { return { name: c, count: cts.frequency(c) }})
  .sort((a, b) => b.count - a.count)
  .reduce((prev, item) => prev + '\r' + item.count + ': ' + item.name, '');

Returns Iterant An new Iterant instance the wraps the passed in iterable

iterable

Properties

Symbol.iterator

Gets the iterator associated with the underlying concrete iterable.

Symbol.toStringTag

The type name that shows up in {@Obejct#toString}.

map

Applys a function to each item of the current iterable and returns a new iterable.

Parameters

  • fct function The function to apply
  • that any? What this should mean when calling fct (i.e. the first parameter of Function.prototype.call) (optional, default null)

Returns Iterable A new Iterable containing the mapped items

reduce

Accumulate an aggregate value over all of an Iterable instance’s items.

Parameters

  • reducer function The function that takes the previous value and the current item and returns a new value for the next iteration. - prev (any) The accumulated value returned from the previous iteration
    • item (any) The current item
    • index (number) The current index
    • self (Iterant)
  • init any The initial value

Examples

Iterant([1, 2, 3])
  .reduce((prev, item) => prev + item, 0);

// First iteration:  (0, 1) => 1
// Second iteration: (1, 2) => 3
// Third iteration:  (3, 3) => 6
// Final result: 6

Returns any The accumlated value

slice

Get a subsection of an Iterant as an Iterant as new Iterant. The default implementation naïvely loops from the start of the Iterant to the end. Subclasses delegate to more efficient implementations, delegating to the backing {@Iterable}.

Parameters

  • begin number The zero-based index where to start
  • end number? The zero-based index before which to stop. Defaults to the rest of the {@Iterant}, which could be infinite. (Don’t do that.)

Returns Iterant A new Iterant

filter

Evaluates each item using a supplied predicate function. Returns a new {@Iterant} containing only items for which the predicate returns true.

Warning: filter is almost always better implemented as an upstream query when you’re working with data from a database.

Parameters

  • predicate function A function that is evaluated for each item. Return true to keep the item, false to ignore.- item (any) The current item
    • index (number) The current index
    • self (Iterant)
    • Returns boolean - Whether the current item matches
  • that any?

Returns Iterant A new Iterant with only the matching items

concat

Concatenates items onto the end of an Iterant, returning a new Iterant instance. Iterable instances are flattened. Other types are appended as-is.

Parameters

  • items ...any Items to concatenate

Examples

Iterant([1, 2, 3])
  .concat(4, 5, [6, 7]);
// Iterant([1, 2, 3, 4, 5, 6, 7])

Returns Iterant A new Iterant instance

sort

Sorts the items based on a user-supplied comparator function.

Warning: It’s almost always better to sort upstream. The default implementation eagerly instantiates an Array and sorts using Array#sort.

Parameters

  • comparator function? A function that compares values pairwise. The default converts both values to string and compares codepoints. - a (any) The current item
    • b (any) The next item
    • Returns number - -1 if a < b, 1 if a > b, and 0 if they’re equal.

Returns IterantArray A sorted {@IterantArray}

clone

Creates a new shallow copy of the Iterant.

Examples

const a = Iterant([1, 2, 3]);
const b = a.clone();
a !== b; // true

Returns Iterant A new Iterant instance

toArray

Converts an Iterant to an Array. This is a pass-through for Array~from that’s convenient for chaining.

Examples

function* gen() { for(let i = 0; i < 10; i++) { yield [String(i), i]; }};
Iterant(new Map(gen))
  .toArray();

=>
[ [ '0', 0 ],
  [ '1', 1 ],
  [ '2', 2 ],
  [ '3', 3 ],
  [ '4', 4 ],
  [ '5', 5 ],
  [ '6', 6 ],
  [ '7', 7 ],
  [ '8', 8 ],
  [ '9', 9 ] ]

isIterable

Whether an object is iterable. Only checks for Symbol.iterator. This won’t catch the case where a function implicitly returns a duck-typed iterator. Note that strings are iterable by defintion in the language spec.

Parameters

  • obj any Any object, including null or undefined
  • ignoreStrings boolean? Don’t consider a string iterable. Be careful how you employ this.

Examples

Iterant.isIterable([1, 2, 3]);        // true
Iterant.isIterable('asdf');           // true, unfortunately
Iterant.isIterable('asdf', true)      // false
Iterant.isIterable((function*(){})()) // true
Iterant.isIterable({a: 'A'})          // false

Returns boolean Whether the object is iterable

IterantArray

Extends Iterant

An IterantArray extends Iterant with functionality specific to built-in JavaScript Array instances.

Parameters

Returns IterantArray A new IterantArray

slice

Delegates to Array#slice and returns a new IterantArray.

Parameters

Returns IterantArray

map

Parameters

Returns IterantArray

IterantSequence

Extends Iterant

An IterantSequence extends Iterant with functionality specific to MarkLogic Sequence instances.

Parameters

Returns IterantSequence A new IterantSequence

slice

Returns a shallow copy of a portion of the Iterant into a new IterantSequence object selected from begin to end, not including end. slice does not modify the original IterantSequence.

The implementation delegates to fn.subsequence() under the covers.

Parameters

  • begin number? Zero-based start index. Only positive integers are supported.
  • end number? Zero-based end index, not inclusive.

Examples

const seq = xdmp.databases();      // Sequence<xs.unsignedLong>
const itr = IterantSequence(seq); // IterantSequence<Sequence<xs.unsignedLong>>
itr
 .slice(2, 4)                      // IterantSequence<xs.unsignedLong>
 .map(xdmp.databaseName)           // Iterant<Generator<string>>
 .toArray()                        // Array<string>

// ["Meters" , "Triggers"]

Returns IterantSequence A shallow copy of the sliced Sequence

Iterable

Iterable is a protocol which when implemented allows a JavaScript object to define their iteration behavior, such as what values are looped over in a for..of loop or iterall's forEach function. Many built-in types implement the Iterable protocol, including Array and Map.

While described by the ES2015 version of JavaScript it can be utilized by any version of JavaScript.

Type: Object

Parameters

  • iterable

Properties

  • Symbol.iterator function (): Iterator<T> A method which produces an Iterator for this Iterable.

Iterator

Iterator is a protocol which describes a standard way to produce a sequence of values, typically the values of the Iterable represented by this Iterator.

While described by the ES2015 version of JavaScript it can be utilized by any version of JavaScript.

Type: Object

Parameters

  • iterable

Properties

  • next function (): {value: T, done: boolean} A method which produces either the next value in a sequence or a result where the done property is true indicating the end of the Iterator.

About

Wraps any JavaScript iterable to provide a common set of chainable methods

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published