Skip to content

Instantly share code, notes, and snippets.

@monfera
Last active August 8, 2016 21:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monfera/4259d1f2e615daeeae96 to your computer and use it in GitHub Desktop.
Save monfera/4259d1f2e615daeeae96 to your computer and use it in GitHub Desktop.
D3.js with FRP (Functional Reactive Programming) and Transducers [UNLISTED]
license: gpl-3.0

D3.js with FRP (Functional Reactive Programming) and Transducers

A skeleton version of a d3.js scatterplot is getting updated asynchronously with data via Functional Reactive Programming. Uses kefir, but it would be similar with bacon or RxJS.

See my newer version with Kefir and transducers-js.

A Pen by Robert Monfera on CodePen.

License.

<script src="http://cdn.cognitect.com/transducers/transducers-0.4.158-min.js"></script>
<script src="https://pozadi.github.io/kefir/dist/kefir.min.js"></script>
/**
* D3 with FRP (Kefir)
*/
let width = 1920, height = 500;
let frp = Kefir;
let svg = d3.select('body').append('svg').attr('width', width).attr('height', height);
let clock = frp.interval(1000, null);
let counter = clock.scan(function(prev, next) {
return prev + 1;
}, 0);
let data = counter.scan(function(prev, next) {
return prev.concat([{
key: next,
x: width * Math.random(),
y: height * Math.random(),
size: 5 + Math.random() * 100,
color: 'rgb(' + [Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256)].join(',') + ')'
}])
}, []);
data.onValue(function(d) {
render(d);
});
/* Old, synchronous version
let data = Array.apply(null, Array(100)).map(function(d, i) {
return {
key: i,
x: width * Math.random(),
y: height * Math.random()
};
});
*/
function render(data) {
let scatterPoints = svg.selectAll('circle').data(data, _.property('key'));
scatterPoints.enter().append('circle')
.attr('cx', _.property('x'))
.attr('cy', _.property('y'))
.attr('r', _.property('size'))
.attr('fill', _.property('color'))
.attr('opacity', 0)
.transition().duration(1000)
.attr('opacity', 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment