Skip to content

Instantly share code, notes, and snippets.

@javierarilos
Last active January 27, 2016 13:49
Show Gist options
  • Save javierarilos/ca5644c761c290637d43 to your computer and use it in GitHub Desktop.
Save javierarilos/ca5644c761c290637d43 to your computer and use it in GitHub Desktop.
Main examples from Martin Fowler article on Collection Pipeline programming pattern with javascript and underscore.js
'use strict';
/**
* Implementing main examples from Martin Fowler article
* on Collection Pipeline programming pattern:
* http://martinfowler.com/articles/collection-pipeline/
* with #javascript and underscore.js: http://underscorejs.org/
*
* tested with nodejs v0.10.32
*
* underscore.js is required:
* $npm install underscore
*/
var _ = require('underscore');
var articles = [
{title: 'NoDBA',
words: 561,
tags: ['nosql', 'people', 'orm'],
type: ':bliki'},
{title: 'Infodeck',
words: 1145,
tags: ['nosql', 'writing'],
type: ':bliki'},
{title: 'OrmHate',
words: 1718,
tags: ['nosql', 'orm'],
type: ':bliki'},
{title: 'ruby',
words: 1313,
tags: ['ruby'],
type: ':article'},
{title: 'DDD_Aggregate',
words: 482,
tags: ['nosql', 'ddd'],
type: ':bliki'}];
// count words _
var result = _.chain(articles).map('words').reduce(function(w, a){return w+a}).value();
console.log('wordcount: ', result);
// count articles by type (as in Fowler's article)
result = _.chain(articles)
.groupBy('type')
.map(function(value, key) {return [key, value.length];})
.object()
.value();
console.log('articles by type (original): ', result);
// count articles by type (using Underscore's countBy function)
result = _(articles).countBy('type');
console.log('articles by type (_.countBy): ', result);
// count number of articles for each tag
result = _.chain(articles)
.map(function(article){return _(article.tags).map(function(tag){return [tag, article];})})
.flatten(true)
.reduce(function(o, a){o[a[0]] ? o[a[0]].push(a[1]) : o[a[0]] = [a[1]]; return o;}, {})
.map(function(articleList,tag){return [tag, {'articles': articleList.length, 'words': _.reduce(articleList, function(w, a){return w + a.words}, 0)}];})
.object()
.value();
console.log('articles for each tag:', result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment