RxJs Bifurcation Diagram

Fractal using RxJs

by Jeremy Likness

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>
<div id="myDiv" style="width: 400px; height: 400px; background: black; margin-left: -5px; margin-top: -5px; padding: 0px;">
</div>

JavaScript

(function() {

  // based on the equation x{n + 1} = x{n} * r * (1.0 - x{n});
  // x represent a % of population, r represents the environment
  // we iterate through r, pick a random x and iterate, then start plotting 
  
  // for richer detail increase the width/height of the div in HTML and/or 
  // increase the iterations

  // generate a step per pixel that we have to work with (r = 0 .. 4)
  var rIterator = function(width) {
      return Rx.Observable.range(0, width - 1).delay(0).map(function(x) {
        return (4.0 * x) / width;
      });
    },

    // generate an iteration to return the next y-axis value
    xIterator = function(r) {
      var x = Math.random();
      return Rx.Observable.interval(0).map(function(i) {
        x = x * r * (1.0 - x);
        return x;
      });
    },

    // quickly compute left offset 
    left = function(r, width) {
      return Math.floor(r * width / 4.0);
    },

    // quickly compute top offset 
    top = function(x, height) {
      return height - Math.floor(x * height);
    },

    div = document.getElementById('myDiv'),
    width = div.clientWidth,
    height = div.clientHeight,
    iterations = 100;

  // for each r step compute the x steps and stuff a div with that color
  rIterator(width).subscribe(function(r) {
    xIterator(r).skip(50).take(iterations).distinct().subscribe(function(x, i) {
      var pixel = document.createElement('div');
      pixel.style.width = pixel.style.height = "1px";
      pixel.style.position = 'absolute';
      pixel.style.background = 'white';
      pixel.style.left = left(r, width) + 'px';
      pixel.style.top = top(x, height) + 'px';
      div.appendChild(pixel);
    })
  });

})();