• Stars
    star
    771
  • Rank 58,729 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🏄 Asynchronous flow control with a functional taste to it

contra.png

Asynchronous flow control with a functional taste to it

λ aims to stay small and simple, while powerful. Inspired by async and lodash. Methods are implemented individually and not as part of a whole. That design helps when considering to export functions individually. If you need all the methods in async, then stick with it. Otherwise, you might want to check λ out!

Feature requests will be considered on a case-by-case basis.

Quick Links

API

Flow Control

Functional

Uncategorized

Install

Install using npm or bower. Or get the source code and embed that in a <script> tag.

npm i contra --save
bower i contra --save

You can use it as a Common.JS module, or embed it directly in your HTML.

var λ = require('contra');
<script src='contra.js'></script>
<script>
var λ = contra;
</script>

The only reason contra isn't published as λ directly is to make it easier for you to type.

Back to top

API

These are the asynchronous flow control methods provided by λ.

λ.waterfall(tasks, done?)

Executes tasks in series. Each step receives the arguments from the previous step.

  • tasks Array of functions with the (...results, next) signature
  • done Optional function with the (err, ...results) signature
λ.waterfall([
  function (next) {
    next(null, 'params for', 'next', 'step');
  },
  function (a, b, c, next) {
    console.log(b);
    // <- 'next'
    next(null, 'ok', 'done');
  }
], function (err, ok, result) {
  console.log(result);
  // <- 'done'
});

Back to top

λ.concurrent(tasks, cap?, done?)

Executes tasks concurrently. Results get passed as an array or hash to an optional done callback. Task order is preserved in results. You can set a concurrency cap, and it's uncapped by default.

  • tasks Collection of functions with the (cb) signature. Can be an array or an object
  • cap Optional concurrency level, used by the internal queue
  • done Optional function with the (err, results) signature
λ.concurrent([
  function (cb) {
    setTimeout(function () {
      cb(null, 'boom');
    }, 1000);
  },
  function (cb) {
    cb(null, 'foo');
  }
], function (err, results) {
  console.log(results);
  // <- ['boom', 'foo']
});

Using objects

λ.concurrent({
  first: function (cb) {
    setTimeout(function () {
      cb(null, 'boom');
    }, 1000);
  },
  second: function (cb) {
    cb(null, 'foo');
  }
}, function (err, results) {
  console.log(results);
  // <- { first: 'boom', second: 'foo' }
});

Back to top

λ.series(tasks, done?)

Effectively an alias for λ.concurrent(tasks, 1, done?).

Executes tasks in series. done gets all the results. Results get passed as an array or hash to an optional done callback. Task order is preserved in results.

  • tasks Collection of functions with the (next) signature. Can be an array or an object
  • done Optional function with the (err, results) signature
λ.series([
  function (next) {
    setTimeout(function () {
      next(null, 'boom');
    }, 1000);
  },
  function (next) {
    next(null, 'foo');
  }
], function (err, results) {
  console.log(results);
  // <- ['boom', 'foo']
});

Using objects

λ.series({
  first: function (next) {
    setTimeout(function () {
      next(null, 'boom');
    }, 1000);
  },
  second: function (next) {
    next(null, 'foo');
  }
}, function (err, results) {
  console.log(results);
  // <- { first: 'boom', second: 'foo' }
});

Back to top

λ.each(items, cap?, iterator, done?)

Applies an iterator to each element in the collection concurrently.

  • items Collection of items. Can be an array or an object
  • cap Optional concurrency level, used by the internal queue
  • iterator(item, key?, cb) Function to execute on each item
    • item The current item
    • key Optional, array/object key of the current item
    • cb Needs to be called when processing for current item is done
  • done Optional function with the (err) signature
λ.each({ thing: 900, another: 23 }, function (item, cb) {
  setTimeout(function () {
    console.log(item);
    cb();
  }, item);
});
// <- 23
// <- 900

Back to top

λ.each.series(items, iterator, done?)

Effectively an alias for λ.each(items, 1, iterator, done?).

Back to top

λ.map(items, cap?, iterator, done?)

Applies an iterator to each element in the collection concurrently. Produces an object with the transformation results. Task order is preserved in the results.

  • items Collection of items. Can be an array or an object
  • cap Optional concurrency level, used by the internal queue
  • iterator(item, key?, cb) Function to execute on each item
    • item The current item
    • key Optional, array/object key of the current item
    • cb Needs to be called when processing for current item is done
  • done Optional function with the (err, results) signature
λ.map({ thing: 900, another: 23 }, function (item, cb) {
  setTimeout(function () {
    cb(null, item * 2);
  }, item);
}, function (err, results) {
  console.log(results);
  <- { thing: 1800, another: 46 }
});

Back to top

λ.map.series(items, iterator, done?)

Effectively an alias for λ.map(items, 1, iterator, done?).

Back to top

λ.filter(items, cap?, iterator, done?)

Applies an iterator to each element in the collection concurrently. Produces an object with the filtered results. Task order is preserved in results.

  • items Collection of items. Can be an array or an object
  • cap Optional concurrency level, used by the internal queue
  • iterator(item, key?, cb) Function to execute on each item
    • item The current item
    • key Optional, array/object key of the current item
    • cb Needs to be called when processing for current item is done
      • err An optional error which will short-circuit the filtering process, calling done
      • keep Truthy will keep the item. Falsy will remove it in the results
  • done Optional function with the (err, results) signature
λ.filter({ thing: 900, another: 23, foo: 69 }, function (item, cb) {
  setTimeout(function () {
    cb(null, item % 23 === 0);
  }, item);
}, function (err, results) {
  console.log(results);
  <- { another: 23, foo: 69 }
});

Back to top

λ.filter.series(items, iterator, done?)

Effectively an alias for λ.filter(items, 1, iterator, done?).

Back to top

λ.queue(worker, cap=1)

Used to create a job queue.

  • worker(job, done) Function to process jobs in the queue
    • job The current job
    • done Needs to be called when processing for current job is done
  • cap Optional concurrency level, defaults to 1 (serial)

Returns a queue you can push or unshift jobs to. You can pause and resume the queue by hand.

  • push(job, done?) Array of jobs or an individual job object. Enqueue those jobs, continue processing (unless paused). Optional callback to run when each job is completed
  • unshift(job, done?) Array of jobs or an individual job object. Add jobs to the top of the queue, continue processing (unless paused). Optional callback to run when each job is completed
  • pending Property. Jobs that haven't started processing yet
  • length Short-hand for pending.length, only works if getters can be defined
  • pause() Stop processing jobs. Those already being processed will run to completion
  • resume() Start processing jobs again, after a pause()
  • on('drain', fn) Execute fn whenever there's no more pending (or running) jobs and processing is requested. Processing can be requested using resume, push, or unshift
var q = λ.queue(worker);

function worker (job, done) {
  console.log(job);
  done(null);
}

q.push('job', function () {
  console.log('this job is done!');
});

q.push(['some', 'more'], function () {
  console.log('one of these jobs is done!');
});

q.on('drain', function () {
  console.log('all done!');
  // if you enqueue more tasks now, then drain
  // will fire again when pending.length reaches 0
});

// <- 'this job is done!'
// <- 'one of these jobs is done!'
// <- 'one of these jobs is done!'
// <- 'all done!'

Back to top

λ.emitter(thing={}, options={})

Augments thing with the event emitter methods listed below. If thing isn't provided, an event emitter is created for you. Emitter methods return the thing for chaining.

  • thing Optional. Writable JavaScript object
  • emit(type, ...arguments) Emits an event of type type, passing any ...arguments
  • emitterSnapshot(type) Returns a function you can call, passing any ...arguments
  • on(type, fn) Registers an event listener fn for type events
  • once(type, fn) Same as on, but the listener is discarded after one callback
  • off(type, fn) Unregisters an event listener fn from type events
  • off(type) Unregisters all event listeners from type events
  • off() Unregisters all event listeners

The emitterSnapshot(type) method lets you remove all event listeners before emitting an event that might add more event listeners which shouldn't be removed. In the example below, thing removes all events and then emits a 'destroy' event, resulting in a 'create' event handler being attached. If we just used thing.off() after emitting the destroy event, the 'create' event handler would be wiped out too (or the consumer would have to know implementation details as to avoid this issue).

var thing = λ.emitter();

thing.on('foo', foo);
thing.on('bar', bar);
thing.on('destroy', function () {
  thing.on('create', reinitialize);
});

var destroy = thing.emitterSnapshot('destroy');
thing.off();
destroy();

The emitter can be configured with the following options, too.

  • async Debounce listeners asynchronously. By default they're executed in sequence.
  • throws Throw an exception if an error event is emitted and no listeners are defined. Defaults to true.
var thing = λ.emitter(); // also, λ.emitter({ foo: 'bar' })

thing.once('something', function (level) {
  console.log('something FIRST TROLL');
});

thing.on('something', function (level) {
  console.log('something level ' + level);
});

thing.emit('something', 4);
thing.emit('something', 5);
// <- 'something FIRST TROLL'
// <- 'something level 4'
// <- 'something level 5'

Returns thing.

Events of type error have a special behavior. λ.emitter will throw if there are no error listeners when an error event is emitted. This behavior can be turned off setting throws: false in the options.

var thing = { foo: 'bar' };

λ.emitter(thing);

thing.emit('error', 'foo');
<- throws 'foo'

If an 'error' listener is registered, then it'll work just like any other event type.

var thing = { foo: 'bar' };

λ.emitter(thing);

thing.on('error', function (err) {
  console.log(err);
});

thing.emit('error', 'foo');
<- 'foo'

Back to top

λ.curry(fn, ...arguments)

Returns a function bound with some arguments and a next callback.

λ.curry(fn, 1, 3, 5);
// <- function (next) { fn(1, 3, 5, next); }

Back to top

Comparison with async

async λ
Aimed at Noders Tailored for browsers
Arrays for some, collections for others Collections for everyone!
apply curry
parallel concurrent
parallelLimit concurrent
mapSeries map.series
More comprehensive More focused
~29.6k (minified, uncompressed) ~2.7k (minified, uncompressed)

λ isn't meant to be a replacement for async. It aims to provide a more focused library, and a bit more consistency.

Back to top

Browser Support

Browser Support

If you need support for one of the legacy browsers listed below, you'll need contra.shim.js.

  • IE < 10
  • Safari < 6
  • Opera < 16
require('contra/shim');
var λ = require('contra');
<script src='contra.shim.js'></script>
<script src='contra.js'></script>
<script>
var λ = contra;
</script>

The shim currently clocks around ~1.2k minified, uncompressed.

Back to top

License

MIT

Back to top

More Repositories

1

dragula

👌 Drag and drop so simple it hurts
JavaScript
21,936
star
2

es6

🌟 ES6 Overview in 350 Bullet Points
4,328
star
3

rome

📆 Customizable date (and time) picker. Opt-in UI, no jQuery!
JavaScript
2,913
star
4

js

🎨 A JavaScript Quality Guide
2,874
star
5

fuzzysearch

🔮 Tiny and blazing-fast fuzzy search in JavaScript
JavaScript
2,711
star
6

woofmark

🐕 Barking up the DOM tree. A modular, progressive, and beautiful Markdown and HTML editor
JavaScript
1,624
star
7

promisees

📨 Promise visualization playground for the adventurous
JavaScript
1,199
star
8

horsey

🐴 Progressive and customizable autocomplete component
JavaScript
1,167
star
9

css

🎨 CSS: The Good Parts
992
star
10

react-dragula

👌 Drag and drop so simple it hurts
JavaScript
992
star
11

shots

🔫 pull down the entire Internet into a single animated gif.
JavaScript
728
star
12

insignia

🔖 Customizable tag input. Progressive. No non-sense!
JavaScript
674
star
13

campaign

💌 Compose responsive email templates easily, fill them with models, and send them out.
JavaScript
641
star
14

perfschool

🌊 Navigate the #perfmatters salt marsh waters in this NodeSchool workshopper
CSS
630
star
15

local-storage

🛅 A simplified localStorage API that just works
JavaScript
523
star
16

angularjs-dragula

👌 Drag and drop so simple it hurts
HTML
509
star
17

reads

📚 A list of physical books I own and read
486
star
18

insane

😾 Lean and configurable whitelist-oriented HTML sanitizer
JavaScript
449
star
19

hget

👏 Render websites in plain text from your terminal
HTML
334
star
20

hit-that

✊ Render beautiful pixel perfect representations of websites in your terminal
JavaScript
332
star
21

hash-sum

🎊 Blazing fast unique hash generator
JavaScript
301
star
22

swivel

Message passing between ServiceWorker and pages made simple
JavaScript
294
star
23

dominus

💉 Lean DOM Manipulation
JavaScript
277
star
24

trunc-html

📐 truncate html by text length
JavaScript
220
star
25

grunt-ec2

📦 Create, deploy to, and shutdown Amazon EC2 instances
JavaScript
190
star
26

beautify-text

✒️ Automated typographic quotation and punctuation marks
JavaScript
186
star
27

sixflix

🎬 Detects whether a host environment supports ES6. Algorithm by Netflix.
JavaScript
175
star
28

twitter-for-github

🐥 Twitter handles for GitHub
JavaScript
146
star
29

awesome-badges

🏆 Awesome, badges!
JavaScript
124
star
30

prop-tc39

Scraping microservice for TC39 proposals 😸
JavaScript
108
star
31

megamark

😻 Markdown with easy tokenization, a fast highlighter, and a lean HTML sanitizer
JavaScript
104
star
32

diferente

User-friendly virtual DOM diffing
JavaScript
95
star
33

domador

😼 Dependency-free and lean DOM parser that outputs Markdown
JavaScript
86
star
34

proposal-undefined-coalescing-operator

Undefined Coalescing Operator proposal for ECMAScript
77
star
35

dotfiles

💠 Yay! @bevacqua does dotfiles \o/
Shell
75
star
36

assignment

😿 Assign property objects onto other objects, recursively
JavaScript
73
star
37

sektor

📍 A slim alternative to jQuery's Sizzle
JavaScript
65
star
38

map-tag

🏷 Map template literal expression interpolations with ease.
JavaScript
65
star
39

unbox

Unbox a node application with a well-designed build-oriented approach in minutes
JavaScript
61
star
40

hint

Awesome tooltips at your fingertips
JavaScript
60
star
41

but

🛰 But expands your functional horizons to the edge of the universe
JavaScript
59
star
42

kanye

Smash your keyboards with ease
JavaScript
55
star
43

correcthorse

See XKCD for reference
JavaScript
52
star
44

easymap

🗺 simplified use of Google Maps API to render a bunch of markers.
JavaScript
52
star
45

flickr-cats

A demo page using the Flickr API, ServiceWorker, and plain JavaScript
HTML
49
star
46

hubby

👨 Hubby is a lowly attempt to describe public GitHub activity in natural language
JavaScript
46
star
47

ruta3

Route matcher devised for shared rendering JavaScript applications
JavaScript
45
star
48

poser

📯 Create clean arrays, or anything else, which you can safely extend
JavaScript
45
star
49

baal

🐳 Automated, autoscaled, zero-downtime, immutable deployments using plain old bash, Packer, nginx, Node.js, and AWS. Made easy.
Shell
44
star
50

lipstick

💄 sticky sessions for Node.js clustering done responsibly
JavaScript
43
star
51

crossvent

🌏 Cross-platform browser event handling
JavaScript
41
star
52

lazyjs

The minimalist JavaScript loader
JavaScript
39
star
53

spritesmith-cli

😳 Adds a CLI to the spritesmith module
JavaScript
38
star
54

gulp-jsfuck

Fuck JavaScript and obfuscate it using only 6 characters ()+[]!
JavaScript
37
star
55

measly

A measly wrapper around XHR to help you contain your requests
JavaScript
36
star
56

keynote-extractor

🎁 Extract Keynote presentations to JSON and Markdown using a simple script.
AppleScript
35
star
57

hyperterm-working-directory

🖥👷📂 Adds a default working directory setting. Opens new tabs using that working directory.
JavaScript
34
star
58

gitcanvas

🏛 Use your GitHub account's commit history as a canvas. Express the artist in you!
JavaScript
34
star
59

cave

Remove critical CSS from your stylesheet after inlining it in your pages
JavaScript
33
star
60

scrape-metadata

📜 HTML metadata scraper
JavaScript
31
star
61

feeds

🍎 RSS feeds I follow and maintain
31
star
62

suchjs

Provides essential jQuery-like methods for your evergreen browser, in under 200 lines of code. Such small.
JavaScript
30
star
63

ponyedit

An interface between contentEditable and your UI
JavaScript
29
star
64

grunt-grunt

Spawn Grunt tasks in other Gruntfiles easily from a Grunt task
JavaScript
29
star
65

ultramarked

Marked with built-in syntax highlighting and input sanitizing that doesn't encode all HTML.
JavaScript
28
star
66

sell

💰 Cross-browser text input selection made simple
JavaScript
28
star
67

icons

Free icon sets gathered around the open web
27
star
68

insert-rule

Insert rules into a stylesheet programatically with a simple API
JavaScript
26
star
69

hose

Redirect any domain to localhost for convenience or productivity!
JavaScript
26
star
70

ponymark

Next-generation PageDown fork
JavaScript
25
star
71

omnibox

Fast url parsing with a tiny footprint and extensive browser support
JavaScript
25
star
72

estimate

Calculate remaining reading time estimates in real-time
JavaScript
24
star
73

node-emoji-random

Creates a random emoji string. This is as useless as it gets.
JavaScript
24
star
74

sluggish

🐍 Sluggish slug generator that works universally
JavaScript
24
star
75

seleccion

💵 A getSelection polyfill and a setSelection ranch dressing
JavaScript
24
star
76

bullseye

🎯 Attach elements onto their target
JavaScript
23
star
77

vectorcam

🎥 Record gifs out of <svg> elements painlessly
JavaScript
22
star
78

paqui

Dead simple, packager-agnostic package management solution for front-end component developers
JavaScript
22
star
79

grunt-ngdoc

Grunt task for generating documentation using AngularJS' @ngdoc comments
JavaScript
20
star
80

ftco

⚡ Browser extension that unshortens t.co links in TweetDeck and Twitter
JavaScript
19
star
81

jadum

💍 A lean Jade compiler that understands Browserify and reuses partials
JavaScript
19
star
82

trunc-text

📏 truncate text by length, doesn't cut words
JavaScript
16
star
83

flexarea

Pretty flexible areas!
JavaScript
16
star
84

music-manager

📻 Manages a list of favorite artists and opens playlists on youtube.
JavaScript
16
star
85

grunt-integration

Run Integration Tests using Selenium, Mocha, a Server, and a Browser
JavaScript
15
star
86

apartment

🏡 Remove undesirable properties from a piece of css
JavaScript
14
star
87

mongotape

Run integration tests using mongoose and tape
JavaScript
14
star
88

rehearsal

Persist standard input to a file, then simulate real-time program execution.
JavaScript
13
star
89

queso

Turn a plain object into a query string
JavaScript
13
star
90

bitfin

🏦 Finance utility for Bitstamp
JavaScript
13
star
91

pandora-box

🐼 What will it be?
JavaScript
12
star
92

grunt-spriting-example

An example on how to seamlessly use spritesheets with Grunt.
12
star
93

artists

🎤 Big list of artists pulled from Wikipedia.
JavaScript
11
star
94

twitter-leads

🐦 Pull list of leads from a Twitter Ads Lead Generation Card
JavaScript
11
star
95

reaver

Minimal asset hashing CLI and API
JavaScript
11
star
96

atoa

Creates a true array based on `arraylike`, starting at `startIndex`.
JavaScript
10
star
97

BridgeStack

.NET StackExchange API v2.0 client library wrapper
C#
10
star
98

ama

📖 A repository to ask @bevacqua anything.
10
star
99

virtual-host

Create virtual, self-contained `connect` or `express` applications using a very simple API.
JavaScript
10
star
100

banksy

🌇 Street art between woofmark and horsey
JavaScript
10
star