Ejemplo n.º 1
0
Archivo: api.js Proyecto: Jks15063/blog
function _runQuery(opts) {
  opts = opts || {};
  let query = [];
  if(opts.filter) {
    for(let name in opts.filter) {
      query.push(t.filter(x => {
        if(x[name] && x[name].length) {
          return x[name].indexOf(opts.filter[name]) !== -1;
        }
        return x[name] === opts.filter[name];
      }));
    }
  }
  if(opts.select) {
    query.push(t.map(x => {
      return t.toObj(opts.select, t.map(name => [name, x[name]]));
    }));
  }
  if(opts.limit) {
    query.push(t.take(opts.limit));
  }

  var ch = chan(1, query.length ? t.compose.apply(null, query) : null);
  go(function*() {
    var keys = yield db('zrevrange', dbkey('posts'), 0, -1);
    ops.pipe(_getPosts(keys), ch);
  }, { propagate: true });

  return takeAll(ch);
}
Ejemplo n.º 2
0
 it('creates new stream with filter applied', function() {
   var result = [];
   var s1 = stream();
   var tx = t.compose(
     t.map(function(x) { return x * 3; }),
     t.filter(function(x) { return x % 2 === 0; })
   );
   var s2 = flyd.transduce(tx, s1);
   stream([s2], function() { result.push(s2()); });
   s1(1)(2)(3)(4);
   assert.deepEqual(result, [6, 12]);
 });
Ejemplo n.º 3
0
 it('supports dedupe', function() {
   var result = [];
   var s1 = stream();
   var tx = t.compose(
     t.map(function(x) { return x * 2; }),
     t.dedupe()
   );
   var s2 = flyd.transduce(tx, s1);
   stream([s2], function() { result.push(s2()); });
   s1(1)(1)(2)(3)(3)(3)(4);
   assert.deepEqual(result, [2, 4, 6, 8]);
 });
Ejemplo n.º 4
0
	constructor(currency, buf, currValue = 1){
		let xform = transducers.compose(
          transducers.map(item => {return {
			  id: item.id,
			  currency: currency,
			  value: `${currency}${item.value}`,
			  inString: `${item.id} ${currency}${item.value}`
		  }})
    	);
		
		this[channel] = csp.chan(1, xform);
	}
Ejemplo n.º 5
0
 it("should complete when terminated by an earlier reduction", function*() {
   var ch = chan(1, t.compose(t.take(5), t.partition(2)));
   go(function*() {
     assert.equal((yield put(ch, 1)), true);
     assert.equal((yield put(ch, 2)), true);
     assert.equal((yield put(ch, 3)), true);
     assert.equal((yield put(ch, 4)), true);
     assert.equal((yield put(ch, 5)), true);
     assert.equal((yield put(ch, 6)), false);
   });
   assert.deepEqual((yield take(ch)), [1, 2]);
   assert.deepEqual((yield take(ch)), [3, 4]);
   assert.deepEqual((yield take(ch)), [5]);
   assert.deepEqual((yield take(ch)), CLOSED);
 });
Ejemplo n.º 6
0
 it('handles reduced stream and ends', function() {
   var result = [];
   var s1 = stream();
   var tx = t.compose(
     t.map(function(x) { return x * 2; }),
     t.take(3)
   );
   var s2 = flyd.transduce(tx, s1);
   stream([s2], function() { result.push(s2()); });
   s1(1)(2);
   assert.notEqual(true, s2.end());
   s1(3);
   assert.equal(true, s2.end());
   s1(4);
   assert.deepEqual(result, [2, 4, 6]);
 });
Ejemplo n.º 7
0
Archivo: api.js Proyecto: Jks15063/blog
function createPost(shorturl, props = {}) {
  props = _denormalizePost(t.merge({
    date: currentDate(),
    tags: '',
    published: false
  }, props));
  props.shorturl = shorturl;

  return go(function*() {
    if(shorturl === 'new') {
      return csp.Throw(new Error('the url `new` is reserved'));
    }

    let key = dbkey('post', shorturl);
    if(yield db('exists', key)) {
      // A new post cannot overwrite an existing post
      return csp.Throw(new Error('post already exists with url: ' + props.shorturl));
    }
    else {
      yield db('hmset', key, props);
    }

    yield _finalizeEdit(key, props.date);
  }, { propagate: true });
}
Ejemplo n.º 8
0
function bin(series, nrOfBins, extent) {
  series = t.filter(
    series,
    extent
      ? v => Number.isFinite(v) && v <= extent[1] && v >= extent[0]
      : Number.isFinite
  )

  // copy the series before because sort acts inplace
  series = [...series]
  series.sort((a, b) => a - b)

  let len = series.length
  let seriesMin = series[0]
  let seriesMax = series[len - 1]

  const binWidth = (seriesMax - seriesMin) / nrOfBins

  let bins = t.map(
    range(0, nrOfBins),
    i => {
      const isLastBin = i === nrOfBins - 1
      const binMin = seriesMin + i * binWidth
      const binMax = isLastBin ? seriesMax : binMin + binWidth
      return {
        min: binMin,
        max: binMax,
        mid: (binMin + binMax) / 2,
        count: 0
      }
    }
  )

  let seriesIndex = 0
  let binIndex = 0
  while (seriesIndex++ < len) {
    let item = series[seriesIndex]
    while(item > bins[binIndex].max) {
      ++binIndex
    }
    bins[binIndex].count++
  }

  return bins
}
Ejemplo n.º 9
0
 it('creates new stream with map applied', function() {
   var result = [];
   var s1 = stream();
   var tx = t.map(function(x) { return x * 3; });
   var s2 = flyd.transduce(tx, s1);
   stream([s2], function() { result.push(s2()); });
   s1(1)(2)(4)(6);
   assert.deepEqual(result, [3, 6, 12, 18]);
 });
Ejemplo n.º 10
0
 it("should work", function*() {
   var ch = chan(3, t.map(inc));
   go(function*() {
     for (var i = 0; i < 6; i++) {
       yield put(ch, i);
     }
   });
   for (var i = 0; i < 6; i++) {
     assert.equal((yield take(ch)), inc(i));
   }
 });
Ejemplo n.º 11
0
 it("should work", function*() {
   var ch = chan(3, t.filter(even));
   go(function*() {
     for (var i = 0; i < 6; i++) {
       yield put(ch, i);
     }
   });
   assert.equal((yield take(ch)), 0);
   assert.equal((yield take(ch)), 2);
   assert.equal((yield take(ch)), 4);
 });
Ejemplo n.º 12
0
 it("should work", function*() {
   var ch = chan(1, t.drop(3));
   go(function*() {
     assert.equal((yield put(ch, 0)), true);
     assert.equal((yield put(ch, 1)), true);
     assert.equal((yield put(ch, 2)), true);
     assert.equal((yield put(ch, 3)), true);
     assert.equal((yield put(ch, 4)), true);
   });
   assert.equal((yield take(ch)), 3);
   assert.equal((yield take(ch)), 4);
 });
Ejemplo n.º 13
0
 it("should work", function*() {
   var ch = chan(1, t.take(3));
   go(function*() {
     assert.equal((yield put(ch, 0)), true);
     assert.equal((yield put(ch, 1)), true);
     assert.equal((yield put(ch, 2)), true);
     assert.equal((yield put(ch, 3)), false);
   });
   assert.equal((yield take(ch)), 0);
   assert.equal((yield take(ch)), 1);
   assert.equal((yield take(ch)), 2);
   assert.equal((yield take(ch)), CLOSED);
 });
Ejemplo n.º 14
0
Archivo: api.js Proyecto: Jks15063/blog
// JSON type -> db representation
function _denormalizePost(post) {
  // Only use the whitelisted fields
  post = toObj(postFields, t.compose(
    t.map(x => post[x] !== undefined ? [x, post[x]] : null),
    t.filter(x => x)
  ));

  if(post.tags) {
    post.tags = filter(map(post.tags, x => x.trim().replace(/ /g, '-')),
                       x => x.length).join(',');
  }
  if(post.date) {
    post.date = post.date.toString();
  }
  if(post.published !== undefined) {
    post.published = post.published ? 'y' : 'n';
  }
  if(post.headerimgfull !== undefined) {
    post.headerimgfull = post.headerimgfull ? 'y' : 'n';
  }
  return post;
}
Ejemplo n.º 15
0
var matcher = function(records, query, type, wildcard) {
    var filterAndMap = T.compose(
        T.filter(onlySimilar.bind({ query : query })),
        T.filter(onlyRecordType.bind({ recordType : type })),
        T.map(intoResponses.bind({  recordType : type })),
        T.map(intoGroups.bind({ query : query, wildcard : wildcard }))
    );
    return T.transduce(records, filterAndMap, transformer);
};
Ejemplo n.º 16
0
 it("should complete when terminated from outside", function*() {
   var ch = chan(1, t.partition(2));
   go(function*() {
     yield put(ch, 1);
     yield put(ch, 2);
     yield put(ch, 3);
     yield put(ch, 4);
     yield put(ch, 5);
     ch.close();
   });
   assert.deepEqual((yield take(ch)), [1, 2]);
   assert.deepEqual((yield take(ch)), [3, 4]);
   assert.deepEqual((yield take(ch)), [5]);
   assert.deepEqual((yield take(ch)), CLOSED);
 });
Ejemplo n.º 17
0
    it("should flush multiple pending puts when a value is taken off the buffer", function*() {
      var ch = chan(1, t.partition(3));
      var count = 0;
      var inc = function() {
        count += 1;
      };
      yield put(ch, 1);
      yield put(ch, 1);
      yield put(ch, 1);

      putAsync(ch, 1, inc);
      putAsync(ch, 1, inc);
      putAsync(ch, 1, inc);
      yield take(ch);
      assert.equal(count, 3);
    });
Ejemplo n.º 18
0
  render: function() {
    if(!this.state.post) {
      return div(null, 'Loading...');
    }

    let post = t.merge({ date: '19840620' }, this.state.post);

    // The data property is a littly funky because usually it's set up
    // by the data fetching layer, but we just want to render a fake
    // post
    return Post({
      data: {
        post: {
          post: post
        }
      }
    });
  }
Ejemplo n.º 19
0
    if (odd(entry)) {
      result[count] = entry;
      count++;
    }

    index++;
  }

  result.length = count;
  return result;
}

var transducer = t.compose(
  t.cat,
  t.map(square),
  t.filter(odd),
  t.take(20)
);

if (t.seq) {
  t.sequence = t.seq;
}

//while(true) {
//  var result = t.sequence(transducer, [range]);
//}

require('../bench')([
  { name: 'native',      fn: function() { var result = native(range, 20);               } },
  { name: 'lodash',      fn: function() { var result = lodash(range, 20);               } },
  { name: 'transducer',  fn: function() { var result = t.sequence(transducer, [range]); } },
Ejemplo n.º 20
0
export default function(req, res) {
  var arr = JSON.parse(req.query.arr || '[]');
  res.send(t.map(arr, function(x) { return x + 1; }));
};
Ejemplo n.º 21
0
Archivo: api.js Proyecto: kenarai/blog
 posts = posts.map(x => {
   return t.toObj(opts.select, t.map(name => [name, x[name]]));
 });
Ejemplo n.º 22
0
Archivo: api.js Proyecto: Jks15063/blog
 query.push(t.map(x => {
   return t.toObj(opts.select, t.map(name => [name, x[name]]));
 }));
Ejemplo n.º 23
0

// Slight edit to the function so it can now take a channel.
function listen (el, action, ch) {
    ch = ch || chan();

    el.addEventListener(action, function (event) {
        putAsync(ch, event);
    });

    return ch;
}

var getCoordinates = transducers.map(function (event) {
    return {
        x: event.clientX,
        y: event.clientY
    };
});

// Our "main" function. Asks the `listen` function to listen for mousemoves,
// and sets up a loop that responds to new events.
go(function* () {
    var el = document.getElementById('ui-box'),
        ch = listen(el, 'mousemove', chan(1, getCoordinates));

    while (true) {
        // Logs the coordinates.
        console.log(yield take(ch));
    }
});
Ejemplo n.º 24
0
Archivo: api.js Proyecto: Jks15063/blog
function queryDrafts(query) {
  query.filter = t.merge(query.filter || {}, { published: false });
  return _runQuery(query);
}
Ejemplo n.º 25
0
Archivo: api.js Proyecto: Jks15063/blog
function queryPosts(query) {
  query.filter = t.merge(query.filter || {}, { published: true });
  return _runQuery(query);
}
Ejemplo n.º 26
0
async(function*() {
  var ms = 5;
  var triangles, val, timer, i;

  var xf = t.compose(
    tx.mapcat(function(x) { return [x, x*x]; }),
    t.take(14),
    t.partitionBy(function(x) { return x % 3; }),
    t.filter(function(x) { return x.length > 1; }),
    t.map(function(x) { return x.join('#'); })
  );

  console.log('Some complicated transformation:');
  console.log();
  console.log('expected: '+JSON.stringify(t.seq(a, xf))); 
  console.log('got     : '+JSON.stringify(yield channelToArray(tchan(xf, 1))));
  console.log();

  console.log();
  console.log('Triangle numbers:');
  console.log();
  triangles = tchan(t.compose(sums, sums), 1);

  console.log('Taking the first 5 numbers:');

  for (i = 0; i < 5; ++i)
    console.log(yield csp.pull(triangles));

  console.log();
  console.log('Taking further numbers for ' + ms + ' miliseconds:');

  timer = csp.timeout(ms);
  while (undefined !== (val = (yield csp.select(timer, triangles)).value))
    console.log(val);

  console.log();
  console.log('Taking 5 more numbers:');

  for (i = 0; i < 5; ++i)
    console.log((yield csp.select(triangles)).value);

  csp.close(triangles);
  console.log();

  console.log();
  console.log('Sort & take:');
  console.log();

  xf = t.compose(
    t.take(20),
    tx.sort(function(a, b) { return (a%7) - (b%7); }),
    t.take(10)
  );

  console.log('expected: '+JSON.stringify(t.seq(a, xf))); 
  console.log('got     : '+JSON.stringify(yield channelToArray(tchan(xf, 1))));  
});
Ejemplo n.º 27
0

// Slight edit to the function so it can now take a channel.
function listen (el, action, ch) {
    ch = ch || chan();

    el.addEventListener(action, function (event) {
        putAsync(ch, event);
    });

    return ch;
}

var getCoordinates = transducers.map(function (event) {
        return {
            x: event.clientX,
            y: event.clientY
        };
    }),
    filterEvenCoordinates = transducers.filter(function (coordinates) {
        var xIsEven = coordinates.x % 2 === 0,
            yIsEven = coordinates.y % 2 === 0;

        return xIsEven && yIsEven;
    }),
    // Notice that unlike most other compose functions, this one composes from
    // left to right.
    eventToEventCoordinates = transducers.compose(getCoordinates, filterEvenCoordinates);

// Our "main" function. Asks the `listen` function to listen for mousemoves,
// and sets up a loop that responds to new events.
go(function* () {
Ejemplo n.º 28
0
 { name: 'transducer',  fn: function() { var result = t.sequence(transducer, [range]); } },