0.2.3 • Published 5 years ago

@lxsmnsyc/iterable-js v0.2.3

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

iterable-js

An extensions for objects with Iteration Protocol for JS

npm.io

PlatformBuild Status
LinuxBuild Status
WindowsBuild status

codecov

Introduction

Iterations Protocol

ES2015 introduces a new feature, namely the Iterations Protocol. The protocol consists of 2 protocols:

  • The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for..of construct. Some built-in types are built-in iterables with a default iteration behavior, such as Array or Map, while other types (such as Object) are not.

    In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant Symbol.iterator:

    • [Symbol.iterator]
      • A zero arguments function that returns an object, conforming to the iterator protocol.

    Whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.

  • The iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.

    An object is an iterator when it implements a next() method with the following semantics:

    • next
      • A zero arguments function that returns an object with at least the following two properties:
        • done (boolean)
          • Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator.
          • Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether.
        • value
          • any JavaScript value returned by the iterator.
          • Can be omitted when done is true.
      • The next method always has to return an object with appropriate properties including done and value.
      • If a non-object value gets returned (such as false or undefined), a TypeError ("iterator.next() returned a non-object value") will be thrown.

Iterable and Iteration Protocol

Iterable intends to unify all iterable objects, be it a built-in iterable (e.g. Array, String, Map) or a user-made iterable (e.g. user-defined generators, objects with Symbol.iterator property), acting as the de-facto superset.

By taking advantage of the Iteration Protocol, Iterable can provide operators that allows to transform any iterable objects.

Iterable operators are not strict to Iterable instance, they expect the first parameters to be an iterable object, regardless of the implementation. For example,

Iterable.concat('Hello', [1, 2, 3, 4, 5]);

creates an iterable that yields the characters of 'Hello' and the values of [1, 2, 3, 4, 5] sequentially.

Iterable vs IxJS

First, I would like to point out that at the time I have written almost half of the library, I stumbled upon the library IxJS while looking for Rx libraries, and to my surprise, it has the same goal as my library's.

So, what are the differences?

Iterable doesn't/isn't:

  • support async.
  • expose the operators as an individual module.
  • written in TypeScript.
  • have operators that returns a single value from an aggregation (e.g reduce), instead, they are considered as a singular Iterable (an Iterable with one element).
  • handle errors.

Iterable does/is:

  • support chaining operators for an Iterable as well as provide these operators as a static member, allowing class deconstruction.
  • allow bracket notation for accessing the nth-yield of the Iterable.
  • throw runtime errors. If an error occurs, the errors are thrown synchronously on iteration.
  • know if an object is iterable by concept or not, allowing non-Iterable instances to have access with the Iterable operators.

Method Counterparts

IterableIxJSNotes
alleveryReturns a singular Iterable that yields the boolean result.
anysomeReturns a singular Iterable that yields the boolean result.
averageaverageReturns a singular Iterable that yields the number result.
breadthFirst
breakWith
bufferbufferDoesn't have the skip mechanism.
cache
composepipe
concatconcat, of, endWithUnlike the IxJS concat, Iterable concat allows to concat non-Iterable values.
containsincludesDoesn't have the skip mechanism. Returns a singular Iterable that yields the boolean result.
countcountReturns a singular Iterable that yields the number result.
defaultIfEmptydefaultIfEmpty
depthFirst
diff
distinctdistinctDoesn't have the compare mechanism. Strict equality is used.
distinctAdjacentdistinctUntilChangedDoesn't have the compare mechanism. Strict equality is used.
doWhiledoWhile
elementAtelementAtReturns a singular Iterable that yields the result.
emptyempty
equalsequenceEqualReturns a singular Iterable that yields the boolean result.
filterfilter
findfindInstead of yielding the passing value, `find yields the index. Returns a singular Iterable that yields the number result.
firstfirstReturns a singular Iterable that yields the result.
flatflattenIterable flat only flattens a single layer. To flatten all layers, use depthFirst
flatMapflatMap
ignoreElementsignoreElements
indexOf
innerJoininnerJoin
intercalate
intersectintersect
intersperse
isEmptyisEmptyReturns a singular Iterable that yields the boolean result.
just
lastlast
leftJoin
mapmap
maxmaxReturns a singular Iterable that yields the result.
minminReturns a singular Iterable that yields the result.
onDone
onStart
onYield
outerJoin
partitionpartition
rangerangeUnlike IxJS, Iterable range allows negative slope, and custom step size.
reducereduceReturns a singular Iterable that yields the result.
reduceRightreduceRightReturns a singular Iterable that yields the result.
repeatrepeat
replace
reversereverse
scanscan
scanRightscanRight
skipskip
skipLastskipLast
skipUntil
skipWhileskipWhile
sortorderBy
sortedReturns a singular Iterable that yields the boolean result.
spanWith
split
startWithstartWith
step
sumsumReturns a singular Iterable that yields the result.
taketake
takeLasttakeLast
takeUntil
takeWhiletakeWhile
toArraytoArray
whileDowhile
zipzip
case
catchIterable throws the error synchronously.
catchWithIterable throws the error synchronously.
chain
concatAll
deferMeh
expand
find
for
generateIterable supports Generators.
groupBy
groupJoin
if
memoize
ofEntriesUse Object.entries instead.
ofKeysUse Object.keys instead.
ofValuesUse Object.values instead.
onErrorResumeNextIterable doesn't support fallbacks.
pairwise
pluck
publish
retryIterable doesn't support fallbacks.
bashare
singleIsn't encouraged.
tapuse the doXXXX operators.
union

Usage

Installing

NPM

npm install @lxsmnsyc/iterable-js

CDN

  • jsDelivr

<script src="https://cdn.jsdelivr.net/npm/@lxsmnsyc/iterable-js/dist/index.min.js"></script>
  • unpkg

<script src="https://unpkg.com/@lxsmnsyc/iterable-js/dist/index.min.js"></script>

Loading the module

CommonJS

const Iterable = require('iterable-js');

Loading the CommonJS module provides the Iterable class.

Browser

Loading the JavaScript file for the iterable-js provides the Iterable class.

Example

Creates a partition of iterables in which the first iterable yields the even numbers, while the second iterable yields the odd numbers.

const evenOdd = Iterable.range(1, 200).partition(x => x % 2 === 0);

for (const i of evenOdd[0].map(x => `Next Even: ${x}`)) {
  console.log(i);
}
for (const i of evenOdd[1].map(x => `Next Odd: ${x}`)) {
  console.log(i);
}

Static and non-Static

All operators of Iterable are both static and non-static (except for a few ones), allowing chainable and direct transformations.

Both examples below does the same thing.

for (const i of Iterable.filter('Hello World', x => x === x.toUpperCase())) {
  console.log(i);
}
for (const i of new Iterable('Hello World').filter(x => x === x.toUpperCase())) {
  console.log(i);
}

Generators

Iterable treats generator functions as an iterable object, even if it doesn't implement the iterable protocol.

const iterable = new Iterable(function* () {
  yield 1;
  yield 2;
  yield 3;
});
for (const i of iterable) {
  console.log(i);
}

Creating your own operators

To create your own operator, you must pass functions to the compose method. The functions provided must receive a single parameter, which refers to the chained Iterable, and must return an Iterable.

const getOdds = source => source.filter(x => x % 2 === 1);

for (const i of Iterable.range(1, 1000).compose(getOdds)) {
  console.log(i);
}

compose can accept multiple functions, allowing to build pipelines of operators.

Build

Clone the repo then run

npm install

To build distributables, coverages and tests:

npm run build
0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.0

5 years ago