Skip to content

Instantly share code, notes, and snippets.

@itrelease
Created July 5, 2015 14:03
Show Gist options
  • Save itrelease/9981325eed6d2b19330c to your computer and use it in GitHub Desktop.
Save itrelease/9981325eed6d2b19330c to your computer and use it in GitHub Desktop.
Transducers difference?
/* NINJA FP */
function mapping(transform) {
return function (reduce) {
return function (result, input) {
return reduce(result, transform(input));
};
};
}
function filtering(predicate) {
return function (reduce) {
return function (result, input) {
return (
predicate(input) ?
reduce(result, input) :
result
);
};
};
}
function compose(...reducers) {
return (val) => {
let result = val;
reducers.reverse().forEach(r => {
result = r(result);
return result;
});
return result;
};
}
const posts = [
{ author: 'Agatha', text: 'just setting up my pstr' },
{ author: 'Bert', text: 'Ed Balls' },
{ author: 'Agatha', text: '@Bert fancy a thumb war?' },
{ author: 'Charles', text: '#subtweet' },
{ author: 'Bert', text: 'Ed Balls' },
{ author: 'Agatha', text: '@Bert m(' }
];
function graph(result, input) {
result[input.from] = result[input.from] || [];
result[input.from].push(input.to);
return result;
}
const extractMentions = compose(
// Find mentions
filtering(function (post) {
return post.text.match(/^@/);
}),
// Build object with {from, to} keys
mapping(function (post) {
return {
from: post.author,
to: post.text.split(' ').slice(0,1).join('').replace(/^@/, '')
};
})
);
const t = posts.reduce(extractMentions(graph), {});
console.log(t);
/* STRONG FP END */
///////////////
/* AMATEUR FP START */
function transduce(input, reducers) {
return reducers.reduce(function (acc, reducer) {
const args = reducer.args || [];
return acc[reducer.type](reducer.value, ...args);
}, input);
}
const extractMentions = function () {
return [
{
type: 'filter',
value: function (post) {
return post.text.match(/^@/);
}
},
{
type: 'map',
value: function (post) {
return {
from: post.author,
to: post.text.split(' ').slice(0, 1).join('').replace(/^@/, '')
};
}
},
{
type: 'reduce',
value: function (result, post) {
result[post.from] = result[post.from] || [];
result[post.from].push(post.to);
return result;
},
args: [{}]
}
];
};
const posts = [
{ author: 'Agatha', text: 'just setting up my pstr' },
{ author: 'Bert', text: 'Ed Balls' },
{ author: 'Agatha', text: '@Bert fancy a thumb war?' },
{ author: 'Charles', text: '#subtweet' },
{ author: 'Bert', text: 'Ed Balls' },
{ author: 'Agatha', text: '@Bert m(' }
];
const t = transduce(posts, extractMentions());
console.log(t);
/* AMATEUR FP END */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment