How to use baconjs - 10 common examples

To help you get started, we’ve selected a few baconjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github NewbranLTD / gulp-server-io / __tests__ / examples / gulp.js View on Github external
app.use(
  serveStatic(root, {
    index: ['index.html', 'index.htm']
  })
);

// Create server
const server = http.createServer(app);

server.listen(3001, () => {
  console.log(chalk.yellow('Example server start @ 3001'));
  open('http://localhost:3001');
});
let watcher;
// Start the watch files with Bacon wrapper
const streamWatcher = bacon.fromBinder(sink => {
  watcher = chokidar.watch(root, { ignored: /(^|[\/\\])\../ });
  watcher.on('all', (event, path) => {
    sink({ event: event, path: path });
    return () => {
      watcher.unwatch(root);
    };
  });
});
let files = [];
streamWatcher
  .skipDuplicates(_.isEqual)
  .map('.path')
  .doAction(f => files.push(f))
  .debounce(300)
  .onValue(files => {
    if (files.length) {
github sighjs / sigh / test / src / plugin / write.spec.js View on Github external
writeStream.onValue(events => {
        // console.log('write events %j', events)
        if (++nValues === 1) {
          existsSync(TMP_FILE).should.be.ok
          existsSync(TMP_FILE + '.map').should.be.ok
        }
        else {
          existsSync(TMP_FILE).should.not.be.ok
          existsSync(TMP_FILE + '.map').should.not.be.ok
          resolve()
          return Bacon.noMore
        }
      })
      writeStream.onError(reject)
github CleverCloud / clever-tools / src / models / log.js View on Github external
.toProperty();

  const s_appLogs = Application.get(api, appData.app_id)
    .flatMapLatest((app) => {
      Logger.debug('Fetch application logs…');
      if (deploymentId != null) {
        return getAppLogs(app.id, null, null, new Date(), null, deploymentId);
      }
      return s_deploymentStart.flatMapLatest((deploymentStartEvent) => {
        const deploymentId = deploymentStartEvent.data.uuid;
        return getAppLogs(app.id, null, null, new Date(), null, deploymentId);
      });
    });

  // TODO, could be done without a Bus (with merged streams)
  const s_allLogs = new Bacon.Bus();

  s_deploymentStart.onValue(() => {
    s_allLogs.push(colors.bold.blue('Deployment started'));
  });

  s_deploymentEnd.onValue((e) => {
    if (e.data.state === 'OK') {
      s_allLogs.push(colors.bold.green('Deployment successful'));
    }
    else {
      s_allLogs.error('Deployment failed. Please check the logs');
    }
    s_allLogs.end();
  });

  if (!quiet) {
github viddo / atom-textual-velocity / lib / path-watcher-factory.js View on Github external
.flatMap((t: {file: FileType, fileReaders: Array}) => {
          const {filename, stats: fileStats} = t.file

          let fileReaders = t.fileReaders
          if (notes) {
            const note = notes[filename]
            if (note && note.stats.mtime.getTime() === fileStats.mtime.getTime()) {
              fileReaders = fileReaders.filter(fileReader => note[fileReader.notePropName] === undefined)
            }
            if (fileReaders.length === 0) return Bacon.never() // e.g. a cached note that have all read values already
          }

          return Bacon
            .fromArray(fileReaders)
            .flatMap((fileReader: FileReaderType) => {
              const readResult: FileReaderResultType = {
                filename: filename,
                notePropName: fileReader.notePropName,
                value: null
              }
              return Bacon
                .fromNodeCallback(fileReader.read.bind(fileReader), notesPath.fullPath(filename), fileStats)
                .map(value => {
                  readResult.value = value === undefined ? null : value // make sure value cannot be undefined
                  return readResult
                })
                .mapError(err => {
                  console.warn('failed to read file:', err)
                  return readResult
github viddo / atom-textual-velocity / lib / path-watcher-factory.js View on Github external
.fromNodeCallback(fileReader.read.bind(fileReader), notesPath.fullPath(filename), fileStats)
                .map(value => {
                  readResult.value = value === undefined ? null : value // make sure value cannot be undefined
                  return readResult
                })
                .mapError(err => {
                  console.warn('failed to read file:', err)
                  return readResult
                })
            })
        })
    }

    const newFileS = createFileStream('add')

    const fileReaderResultS = Bacon
      .mergeAll(
        createFileReaderResultsStream(newFileS, notesCache),
        createFileReaderResultsStream(createFileStream('change'))
      )

    const updateNoteProps = (note: Object, fields: Array, filename: string) => {
      note.id = process.hrtime().toString()
      fields.forEach(field => {
        if (field.value) {
          note[field.notePropName] = field.value(note, filename)
        }
      })
    }

    const sifterP = Bacon
      .update(
github viddo / atom-textual-velocity / lib / path-watcher-factory.js View on Github external
.flatMap((fileReader: FileReaderType) => {
              const readResult: FileReaderResultType = {
                filename: filename,
                notePropName: fileReader.notePropName,
                value: null
              }
              return Bacon
                .fromNodeCallback(fileReader.read.bind(fileReader), notesPath.fullPath(filename), fileStats)
                .map(value => {
                  readResult.value = value === undefined ? null : value // make sure value cannot be undefined
                  return readResult
                })
                .mapError(err => {
                  console.warn('failed to read file:', err)
                  return readResult
                })
            })
        })
github viddo / atom-textual-velocity / lib / query-task.js View on Github external
const newItemsStream = msgStream.filter(R.propEq('type', 'add')).map(R.prop('item'))
  const removedItemsStream = msgStream.filter(R.propEq('type', 'rm')).map(R.prop('path'))

  const itemsProp = Bacon.update(
    [],
    [newItemsStream], (items, item) => items.concat({
      title: Path.basename(item.path),
      content: fs.readFileSync(item.path, 'utf8')
    }),
    [removedItemsStream], (items, path) => items.filter(item => item.path !== path)
  )
  const sifterProp = itemsProp
    .debounce(50) // avoid creating a new sifter too often
    .map(items => new Sifter(items))

  Bacon.combineWith(sifterProp, queryStream, (sifter, q) =>
      sifter.search(q, {
        fields: ['title', 'content'],
        sort: [{field: 'title', direction: 'asc'}]
      })
    )
    .onValue(r => emit('results', r))

  disposeStream.onValue(terminate)
}
github viddo / atom-textual-velocity / spec / logger-spec.js View on Github external
beforeEach(function () {
      this.filesBus = new Bacon.Bus()
      this.initialPathScanDoneBus = new Bacon.Bus()

      const filesProp = this.filesBus.toProperty()
      const initialPathScanDoneProp = this.initialPathScanDoneBus.map(true).toProperty(false)

      this.prevCallsLength = this.consoleSpy.log.calls.length // to compensate for console logs done previously

      this.logger.logPathScan({filesProp: filesProp, initialPathScanDoneProp: initialPathScanDoneProp})
      R.times((i) => { this.filesBus.push(R.repeat(`file ${i}`, i)) }, 5)
    })
github mikaelbr / bacon-love / exercises / 10_and_or_or_or_maybe_not / exercise.js View on Github external
expect: function (stream, exercise, assert{
        stream.onValue(function (report{
          assert(report !== true);
        });

        c2.push(4000);
      }
    },
    'Should not report if the limit is lower than the flow': {
      input: [
        c3,
        Bacon.constant(false), // inCriticalMode
        Bacon.constant(false), // onBreak
        Bacon.constant(true), // isSingleGate
        Bacon.constant(true), // systemActive
        2000 // riverLimit
      ],

      expect: function (stream, exercise, assert{
        stream.onValue(function (report{
          assert(report !== true);
        });

        c3.push(1000);
      }
    },
    'Should not report if the workers are on a break': {
      input: [
        c4,
        Bacon.constant(false), // inCriticalMode
        Bacon.constant(true), // onBreak
github viddo / atom-textual-velocity / lib / workers / session.js View on Github external
.update(
        ({
          str: '',
          strChanged: true,
          start: 0,
          limit: paginationLimit
        }),
        [this._filterBus], (prev, filter) => {
          var newFilter = R.merge(prev, filter)
          newFilter.strChanged = filter.str !== undefined && filter.str !== prev.str
          return newFilter
        }
      )
      .skipDuplicates(R.equals)

    this._sifterResultProp = Bacon
      .combineTemplate({
        sifter: this._sifterProp,
        sortField: this._sortFieldBus.toProperty(sortField),
        sortDirection: this._changeSortDirectionBus.scan(sortDirection, (a, b) => a === 'desc' ? 'asc' : 'desc'),
        searchStr: this._filterProp.map('.str')
      })
      .map(d => {
        // see https://github.com/brianreavis/sifter.js/#searchquery-options for available configuration options
        return d.sifter.search(d.searchStr, {
          fields: ['name', 'content'],
          sort: [
            {field: d.sortField, direction: d.sortDirection},
            {field: '$score', direction: d.sortDirection}
          ],
          conjunction: 'and'
        })