Skip to content

Instantly share code, notes, and snippets.

@odf
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odf/ae937c46f7f95e9e4e57 to your computer and use it in GitHub Desktop.
Save odf/ae937c46f7f95e9e4e57 to your computer and use it in GitHub Desktop.
Demo for small bug in transducers.js 0.2.3
'use strict';
var t = require('transducers.js');
// -- some hacks to let us copy and paste most of the original library code
var Reduced = t.Reduced;
var reduce = t.reduce;
var compose = t.compose;
var map = t.map;
function isReduced(x) {
return (x instanceof t.Reduced) || (x && x.__transducers_reduced__);
}
function bound(f, ctx, count) {
count = count != null ? count : 1;
if(!ctx) {
return f;
}
else {
switch(count) {
case 1:
return function(x) {
return f.call(ctx, x);
}
case 2:
return function(x, y) {
return f.call(ctx, x, y);
}
default:
return f.bind(ctx);
}
}
}
// -- modified Cat, cat and mapcat
function Cat(xform) {
this.xform = xform;
}
Cat.prototype.init = function() {
return this.xform.init();
};
Cat.prototype.result = function(v) {
return this.xform.result(v);
};
Cat.prototype.step = function(result, input) {
var xform = this.xform;
var newxform = {
init: function() {
return xform.init();
},
result: function(v) {
return v;
},
step: function(result, input) {
var val = xform.step(result, input);
// changed this:
// return isReduced(val) ? deref(val) : val;
// to this:
return isReduced(val) ? new Reduced(val) : val;
}
}
return reduce(input, newxform, result);
};
function cat(xform) {
return new Cat(xform);
}
function mapcat(f, ctx) {
f = bound(f, ctx);
return compose(map(f), cat);
}
// -- test with original and modified versions
var xf_original = t.compose(
t.mapcat(function(x) { return [x, x*x]; }),
t.map(function(x) { console.log('.'+x+'.'); return x; }),
t.take(3)
);
console.log('Original:');
console.log(t.seq([1,2,3,4], xf_original));
var xf_modified = t.compose(
mapcat(function(x) { return [x, x*x]; }),
t.map(function(x) { console.log('.'+x+'.'); return x; }),
t.take(3)
);
console.log();
console.log('Modified:');
console.log(t.seq([1,2,3,4], xf_modified));
Original:
.1.
.1.
.2.
.4.
.3.
.9.
.4.
.16.
[ 1, 1, 2 ]
Modified:
.1.
.1.
.2.
[ 1, 1, 2 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment