Esempio n. 1
0
 .filter(function (row) {
   return R.flip(R.any)(config.filters)(R.curry(filterRow)(R.__, row, extraUris))
 })
let R = require('ramda')

const toUpperCase = x => x.toUpperCase()
const toLowerCase = x => x.toLowerCase()
const exclaim = x => x + "!"


var angry = R.compose(exclaim, toUpperCase)
var lastUpper = R.compose(angry, R.head);
console.log(lastUpper(['jumpkick', 'roundhouse', 'uppercut']))

var snakeCase = R.compose(R.replace(/\s+/ig, '_'), R.toLower);
console.log(snakeCase("this is too MUCH to take!"))

const initials = (name) => name.split(' ').map(compose(toUpperCase, head)).join('. ')

const f = R.map(R.compose(toUpperCase, R.head))
const _initials = R.compose(R.join('. '), f, R.split(' '))
console.log(_initials("Iain The King Diamond"))


// Used for debugging
var trace = R.curry(function(tag, x) {
  console.log(tag, x);
  return x;
});

var dasherize = R.compose(R.join('-'), R.map(R.toLower), trace('after-split'),
  R.split(' '), R.replace(/\s{2,}/ig, ' '));
dasherize('The World is a vampire');
Esempio n. 3
0
let parseTyped = curry((type, data) => {
  if (type && type.meta && type.meta.kind == "maybe") {
    type = type.meta.type
  }

  if (type && type.meta && type.meta.kind == "union") {
    type = type.dispatch(data)
  }

  if (isArray(data)) {
    return map(v => parseTyped(type ? type.meta.type : null, v), data)
  } else if (isPlainObject(data)) {
    return reduce((obj, k) => {
      if (k.includes(".")) {
        // compound key
        let kk = k.split(".")
        obj[kk[0]] = parseTyped(type, {[kk.slice(1).join(".")]: data[k]})
      } else {
        // simple key
        let nextType
        if (type && type.meta && type.meta.kind == "dict") {
          nextType = type.meta.codomain
        } else if (type && type.meta && type.meta.kind == "struct") {
          nextType = type.meta.props[k]
        } // else {
          // TODO do nothing?!
          //console.log(type)
          //throw Error(`Invalid type ${type} for key "${k}"`)
        //}
        obj[k] = parseTyped(nextType, data[k])
      }
      return obj
    }, {}, keys(data))
  } else if (typeof data == "string") {
    let parser = type ? typeToParser.get(type) : identity
    return parser ? parser(data) : parseString(data)
  } else if ((data === 1 || data === 0) && type == Tc.Boolean) { // semi-hack for SQL booleans as tinyints...
    return Boolean(data)
  } else {
    return data
  }
})
Esempio n. 4
0
const db = mongo(config.MONGO_URI, collections);

db.eggs.createIndex({location: '2dsphere'});

const checkCollection = R.contains(R.__, collections);

function processRequest(action) {
    return function(coll) {
        if (!checkCollection(coll)) return Future.reject("invalid collection");

        let args = Array.from(arguments).slice(1);
        return Future((reject, resolve) => {
            db[coll][action].apply(db[coll], args.concat((err, result) => err ? reject(err) : resolve(result)));
        });
    }
}

// String -> (Query, Projection?) -> Future Maybe Document
const findOne = R.curryN(2, R.compose(R.map(S.toMaybe), processRequest('findOne')));

//Clone is used here to avoid mutating the original object
const insert = R.curry((coll, record) => processRequest('insert')(coll, R.clone(record)));

const query = R.curryN(2, processRequest('find'));

const update = R.curryN(3, processRequest('update'));

const remove = R.curryN(2, processRequest('remove'));

module.exports = {db, findOne, insert, query, update, remove};
Esempio n. 5
0
let R = require("ramda")
let {append, curry, drop, pipe, split, update} = require("ramda")

let fst = (xs) => xs[0]

let snd = (xs) => xs[1]

// a -> b -> a
let always = curry((x, y) => x)

// String -> Lens
let lens = curry((path) => {
  return path ?
    R.lensPath(split(".", path)) :
    R.lensPath([])
})

// (a -> Boolean) -> a -> [a] -> [a]
let updateBy = curry((pred, val, array) => {
  let i = findIndex(pred, array);
  if (i >= 0) {
    return update(i, val, array);
  } else {
    return array;
  }
})

// (a -> Boolean) -> (a -> b) -> [a] -> [a]
let adjustBy = curry((pred, adjustFn, array) => {
  let i = findIndex(pred, array);
  if (i >= 0) {
Esempio n. 6
0
/// <reference path="../../typings/main.d.ts" />
'use strict';
let listener = require('./event');
let _ = require('ramda');
let config = require('../../config');

let cachedFilters = {};
/**
 * 检测用户是否被封禁
 */
let checkUserIsBlocked = _.curry((room, blockUsers, hash) => {
	return (blockUsers.indexOf(hash)) > -1;
});
/**
 * 检测文字是否和谐
 */
let validateText = _.curry((room, ignoreRegEx, checkRegEx, str) => {
	checkRegEx.lastIndex = 0;
	let testStr = str.replace(ignoreRegEx, "");
	return !checkRegEx.test(testStr);
});
/**
 * 替换关键字
 */
let replaceKeyword = _.curry((room, regex, str) => {
	return str.replace(regex, "***");
});


function initialize(roomName, forceUpdate) {
	if (cachedFilters[roomName] && !forceUpdate) {
          todoAction = left === 0 ? Todo.Action.UnsetDone() : Todo.Action.SetDone();
    return R.evolve({todos: R.map(Todo.update(todoAction))}, model);
  },
  ClearDone: R.evolve({todos: R.reject(R.prop('done'))}),
  ChangePage: (action, model) => MyRouter.Action.case({
    ViewAll: () => R.evolve({view: R.always('all')}, model),
    ViewActive: () => R.evolve({view: R.always('active')}, model),
    ViewCompleted: () => R.evolve({view: R.always('complete')}, model),
  }, action)
})

// View

const viewTodo = R.curry((action$, todo) => {
  return Todo.view({
    action$: forwardTo(action$, Action.Modify(todo)),
    remove$: forwardTo(action$, R.always(Action.Remove(todo))),
  }, todo)
})

const view = R.curry((action$, model) => {
  const hasTodos = model.todos.length > 0,
        left = R.length(R.reject(R.prop('done'), model.todos)),
        filteredTodos = model.view === 'all'    ? model.todos
                      : model.view === 'active' ? R.reject(R.prop('done'), model.todos)
                                                : R.filter(R.prop('done'), model.todos)
  return h('section.todoapp', [
    h('header.header', [
      h('h1', 'todos'),
      h('input.new-todo', {
        props: {placeholder: 'What needs to be done?',
                value: model.newTitle},
Esempio n. 8
0
                 '===', '==', '>=', '<=', '<', '>', '!=', '!==', 'instanceof'];

const unaryOps = ['++', '--', '~', '!', 'delete', 'void', 'typeof', 'yield', 'throw', 'new'];

// List -> Boolean
const isEmpty = R.whereEq({size: 0});

// Syntax -> Boolean
const isPunctuator = s => s.match('punctuator');
const isKeyword = s => s.match('keyword');
const isParens = s => s.match('parens');
const isBraces = s => s.match('braces');
const isIdentifier = s => s.match('identifier');

// Any -> Syntax -> Boolean
const isVal = R.curry((v, s) => s.val() === v);

// Syntax -> Boolean
const isDot = R.allPass([isPunctuator, isVal('.')]);
const isColon = R.allPass([isPunctuator, isVal(':')]);
const isFunctionKeyword = R.allPass([isKeyword, isVal('function')]);
const isOperator = s => (s.match('punctuator') || s.match('keyword')) &&
                          R.any(R.equals(s.val()),
                                assignOps.concat(binaryOps).concat(unaryOps));
const isNonLiteralKeyword = R.allPass([isKeyword,
                                       s => R.none(R.equals(s.val()), literalKeywords)]);
const isKeywordExprPrefix = R.allPass([isKeyword,
  s => R.any(R.equals(s.val()), ['instanceof', 'typeof', 'delete', 'void',
                                  'yield', 'throw', 'new', 'case'])]);
// List a -> a?
let last = p => p.last();
const introHighlight = R.curry(
	(selector, event) => {
		const $marker = $('body').find('#marker');
		if (!selector) {
			$marker.css({
				display: 'none'
			});
			return;
		}

		const $target = $('body').find(selector);
		const offset = $target.offset();

		// const padding = 5;
		// $marker.css({
		// 	left: offset.left - padding,
		// 	top: offset.top - padding,
		// 	width: $target.outerWidth() + (2 * padding),
		// 	height: $target.outerHeight() + (2 * padding),
		// 	display: 'block',
		// });

		const size = 30;
		const centerX = offset.left - 5;
		const centerY = offset.top - 5;
		$marker.css({
			left: centerX,
			top: centerY,
			width: size,
			height: size,
			borderRadius: size / 2,
			border: 'none',
			background: 'rgba(255, 40, 0, 0.75)',
			display: 'block',
		});
	}
);
Esempio n. 10
0
File: Utils.js Progetto: Yougal/Repo
 */

'use strict'

import PATH from 'path'
import URL from 'url'
import {Observable as O} from 'rx'
import R from 'ramda'
import * as Rx from './RxFP'
import {mux, demux} from 'muxer'
import {MTDError, FILE_SIZE_UNKNOWN} from './Error'

const first = R.nth(0)
const second = R.nth(1)
export const trace = R.curry((msg, value) => {
  console.log(msg, value)
  return value
})
export const demuxFP = R.curry((list, $) => demux($, ...list))
export const demuxFPH = R.curry((list, $) => R.head(demux($, ...list)))
export const BUFFER_SIZE = 1024 * 4
export const NormalizePath = (path) => PATH.resolve(process.cwd(), path)
export const GenerateFileName = (x) => {
  return R.last(URL.parse(x).pathname.split('/')) || Date.now()
}
export const ResolvePath = R.compose(NormalizePath, GenerateFileName)
export const SplitRange = (totalBytes, range) => {
  const delta = Math.round(totalBytes / range)
  const start = R.times((x) => x * delta, range)
  const end = R.times((x) => (x + 1) * delta - 1, range)
  end[range - 1] = totalBytes
  return R.zip(start, end)
Esempio n. 11
0
import { curry, keys, prop, reduce } from 'ramda'

const reduceObjIndexed = curry((reducer, accum, obj) =>
  reduce((acc, key) => reducer(acc, prop(key, obj), key), accum, keys(obj))
)

export default reduceObjIndexed
Esempio n. 12
0
import R from 'ramda';

/*========================================================
=            Curried versions of immutable.js            =
========================================================*/

export const boolUpdater = R.curry((what, toBool, state) => {
    return state.update(what, (what) => toBool);
});

export const getter = R.curry((what, state) => {
    return state.get(what);
});

export const deleter = R.curry((what, state) => {
    return state.delete(what);
});

export const sizer = R.curry(state => {
    return state.size();
});


/*=====  End of Curried versions of immutable.js  ======*/
Esempio n. 13
0
/**
 * Element -> (x -> String) -> (x -> ())
 */
const updateElement = (element, transformer) => R.pipe(transformer, setText(element));


/**
 * Int -> Int -> String
 */
const padWithZeros = R.curry((desiredWidth, value) => {

    const valueStr = value.toString();
    const actualWidth = valueStr.length;

    if ( actualWidth < desiredWidth ) {
        return ZEROS.substring(0, desiredWidth - actualWidth) + valueStr;
    } else {
        return valueStr;
    }
});


/**
 * Int -> String
 */
const pad2 = padWithZeros(2);


/**
 * Date -> String
    // return whichever side that has data
    const xIsNullData = NULL_REGEX.test(x);
    const yIsNullData = NULL_REGEX.test(y);
    if (xIsNullData && yIsNullData) {
      return '';
    } else if (yIsNullData) {
      return x;
    } else if (xIsNullData) {
      return y;
    }
    if (x === y) {
      return y;
    }
    // diff and return whichever side that has strictly more data
    const diffFunc = typeof x === 'string' ? diffWords : diffJson;
    const diffs = diffFunc(x, y);
    if (diffs.filter(diff => diff.removed).length === 0) {
      return y;
    } else if (diffs.filter(diff => diff.added).length === 0) {
      return x;
    }
    const level = CRITICAL_FIELDS.includes(key) ? 'warn' : 'info';
    const strX = key === 'ModuleDescription' ? prune(x, PRUNE_LIMIT) : x;
    const strY = key === 'ModuleDescription' ? prune(y, PRUNE_LIMIT) : y;
    log[level](`module ${moduleCode}'s ${key} is not the same, got:\n1) '${strX}'\n2) '${strY}'`);
    return y;
  }, thisModule, anotherModule);
}

export default R.curry(mergeModuleFields);
const setx = (v) => x = v;

/* Function Composition */
const compose = (a,b) => (c) => a(b(c));
const add1 = (v) => v + 1;
const times2 = (v) => v * 2;
const add1OfTimes2 = compose(add1, times2);
//console.log(add1OfTimes2(3), 7);

const hello = (n) => `Hello ${n}`;
const mr = (n) => `Mr. ${n}`;
const formalGreeting = (n) => hello(mr(n));
//console.log(formalGreeting('Peter'));

/* Function Currying */
var R = require('ramda');
const addc = R.curry((a,b) => a + b);
const add5to = addc(5);
console.log(add5to(2), 7);

const users = [{name: 'chet', age:25}, {name:'joe', age:24}]
// console.log(R.pipe(
//     R.sortBy(R.prop('age')),
//     R.map(R.prop('name')),
//     R.join(', ')
// )(users));

/* Functors */
// objects that implement the map function
const array = [1,2,3,4,5,6];
Esempio n. 16
0
'use strict';

var R = require('ramda');
var Binary = require('./binary');


var extract = R.invoke('extract', []);


var makeMonoid = R.curry(function(identity, binary, v) {

  var thisMonoid    = makeMonoid(identity, binary);
  var curriedBinary = R.curry(binary);

  return {
    extract : R.always(v),
    empty   : R.partial(thisMonoid, identity),
    concat  : R.compose(thisMonoid, curriedBinary(v), extract),
  };
});


var maybeParseBinary = R.ifElse(R.is(Function), R.identity, Binary.getFn);


function Monoid(props) {
  return makeMonoid(props.identity, maybeParseBinary(props.binary));
}


function empty(m) {
import R from 'ramda';
import {describe} from 'meteor/practicalmeteor:mocha';
import {Meteor} from 'meteor/meteor';

export const predicateDescribe = R.curry((pred, title, func) => {
	if (typeof pred != 'function'){
		pred = R.always(pred);
	}
	if (pred()){
		describe(title, func);
	}
});

export const serverDescribe = predicateDescribe(Meteor.isServer);
export const clientDescribe = predicateDescribe(Meteor.isClient);
Esempio n. 18
0
* @instance
* @description Represents presence details of a user. Instance of presence is retrieved every time a user fetches his or someone else's presence.
* @example
* // 'blt12sampleb09157' is uid of an Application user on Built.io Backend
* var user = app.User('blt12sampleb09157');
* user
* .getPresence()
* .then(function(presence){
*    // console.log(presence.getState());
* });
*/
var presenceCons = module.exports = R.curry(function(app,data) {
	var returnObj = {
		toJSON:function(){
			return data;
		},
		data   : data,
		app    : app
	}
	return instanceMethodBuilder.build(module.exports,returnObj);
});

/** Util methods **/
var getData  = R.prop('data');

function getMixinedData(presence){
	return R.mixin({},getData(presence));
}

var set = module.exports.set = R.curry(function(parameter,value,presence){
	var newData           = getMixinedData(presence);
	newData[parameter]    = value;
Esempio n. 19
0
//console.log(Maybe.of(null).map(R.match(/hello/)))
//console.log(Container.of(null).map(R.match(/hello/)))

// pipe composes left-to-right
// const numberOfHellos = R.pipe(R.map(R.match(/hello/)), R.map(R.length))
//const numberOfHellos = R.pipe(Maybe.of(R.match(/hello/)), R.map(R.length))
//Maybe.of('hello world').map(numberOfHellos) // returns: Maybe(1)

//  safeHead :: [a] -> Maybe(a)
const safeHead = xs => Maybe.of(xs[0])
//console.log(safeHead([1,2,3])) // returns: Maybe(1)
//console.log(safeHead([])) // returns: Maybe(null)

//  maybe :: b -> (a -> b) -> Maybe a -> b
const maybe = R.curry((defaultValue, transformFn, m) => {
  return m.isNothing() ? defaultValue : transformFn(m.__value)
})

const maybeResult = safeHead([1, 2, 3])
const getResult = maybe('No data', x => x)
//console.log(getResult(safeHead([1, 2, 3])))
//console.log(getResult(safeHead([])))

Maybe.prototype.getOrElse = function(defaultValue) {
  return this.isNothing() ? defaultValue : this.__value
}

//console.log(safeHead([1, 2, 3]).getOrElse('No data'))
//console.log(safeHead([]).getOrElse('No data'))

import R from 'ramda';
import Promise from 'pinkie-promise';
import binded from 'binded';

const { reject } = binded(Promise);

const errorText = (name, ctor, param) => {
  const expected = R.type(ctor());
  const got = R.type(param);
  return `\`${name}\` should be \`${expected}\`, but got \`${got}\``;
};

// contract :: String -> Constructor -> a
const contract = R.curry((name, ctor, param) => R.unless(
  R.is(ctor),
  () => { throw new TypeError(errorText(name, ctor, param)); }
)(param));

const contractP = R.curry((name, ctor, param) => R.unless(
  R.is(ctor),
  () => reject(new TypeError(errorText(name, ctor, param)))
)(param));


export { contract, contractP };
Esempio n. 21
0
const debug           = require('debug')('PIMPMYSQL:QUERY');
const chalk           = require('chalk');
const _               = require('ramda');
const moment          = require('moment');
const Bluebird        = require('bluebird');
const { randomBytes } = require('crypto');
const { inspect }     = require('util');
const jsonparse       = require('./json-parse');
const nestify         = require('./nestify');
const nullify         = require('./nullify-empty');


const TIMESTAMP_FORMAT = 'YYYY-MM-DD HH:mm:ss';


const bindError = _.curry((fn, sql, params) => fn.bind(null, sql, params));


const idMatch = _.curry((id, obj) => id + '' === obj.id + '');


const dateIsUnix = _.compose(_.equals(0), _.modulo(_.__, 1));


const momentFromString = (date) => moment(new Date(date));


const momentFromDate = _.cond([
  [ _.isNil,         moment ]
, [ moment.isMoment, _.identity ]
, [ dateIsUnix,      moment.unix ]
Esempio n. 22
0
} from 'ramda'
import { getChangedLinesFromDiff } from './lib/git'

const linter = new CLIEngine()
const formatter = linter.getFormatter()

const getChangedFiles = pipeP(
  commitRange => exec('git', ['diff', commitRange, '--name-only', '--diff-filter=ACM']),
  prop('stdout'),
  split('\n'),
  filter(endsWith('.js')),
  map(path.resolve)
)

const getDiff = curry((commitRange, filename) =>
  exec('git', ['diff', commitRange, filename])
    .then(prop('stdout')))

const getChangedFileLineMap = curry((commitRange, filePath) => pipeP(
  getDiff(commitRange),
  getChangedLinesFromDiff,
  objOf('changedLines'),
  assoc('filePath', filePath)
)(filePath))

const lintChangedLines = pipe(
  map(prop('filePath')),
  linter.executeOnFiles.bind(linter)
)

const filterLinterMessages = changedFileLineMap => (linterOutput) => {
Esempio n. 23
0
}

// Maybe

var Maybe = function(x) {
  this.__value = x
}

Maybe.of = function(x) {
  return new Maybe(x);
}

Maybe.prototype.isNothing = function() {
  return (this.__value === null || this.__value === undefined);
}

Maybe.prototype.map = function(f) {
  return this.isNothing() ? Maybe.of(null) : Maybe.of(f(this.__value));
}

Maybe.prototype.join = function() {
  return this.isNothing() ? Maybe.of(null) : this.__value;
}

//  chain :: Monad m => (a -> m b) -> m a -> m b
Maybe.prototype.chain = _.curry(function(f, m){
  return m.map(f).join() // or compose(join, map(f))(m)
})  // a.k.a. flatMap!

module.exports = {Identity, Maybe}
Esempio n. 24
0
    dev: {
      // Each module is executed with eval and //@ sourceURL.
      // The fastest choice
      devtool: 'eval',
      // Switch loaders to debug mode.
      debug: true,
      plugins: {
        hotModuleReplacement: new webpack.HotModuleReplacementPlugin(),
      },
    },
    prod: {
      devtool: 'source-map',
      plugins: {
        dedupe: new webpack.optimize.DedupePlugin(),
        uglifyJs: new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }),
      },
    },
  },
}

// const result = wpk.extend(preset, { profile: 'dev' })

exports.extend = R.curry((_configs, options) => {
  const configs = [preset].concat(_configs)
  options.transformers = R.concat(
    options.transformers || [],
    R.values(transformers)
  )
  return wpk.extend(configs, options)
})
Esempio n. 25
0
  return Promise.error(Boom.badRequest('Invalid Request Object'));
};

// getCredential :: Request -> String:id
const getCredential = compose(get('id'), get('credentials'), get('auth'));

// isValid :: String:id -> Promise(Error, Boolean)
const isValid = require('../../../../plugins/User/').isValid;

// isUserValid :: Request -> Promise(Error, Boolean)
const isUserValid = compose(isValid, getCredential);

// userOK :: Boolean<true> -> Promise(Error, Request)
const userOK = curry((request, ok) =>
  new Promise((resolve, reject) => {
    ok ? resolve(request) : reject(Boom.unauthorized('Invalid User'));
  }));

//userNotOk :: Error -> Promise(Error)
const userNotOk = (err) =>
  Promise.reject(Boom.badImplementation('Server Communication failed', err));

// validateUser :: Request -> Promise(Error, Request)
const validateUser = (request) => isUserValid(request).then(userOK(request)).catch(userNotOk);

// getProjectId :: Request -> String:id
const getProjectId = compose(get('id'), get('params'));

// getProject :: Database -> String:id -> Promise(Error, Project)
const getProject = require('../../../../Project/index').getProjectById;
Esempio n. 26
0
import * as R from "ramda"

const isObject = x => x && x.constructor === Object
const isArray = x => x && x.constructor === Array
const isAggregate = R.anyPass([isObject, isArray])

const descend = R.curry((w2w, w) => isAggregate(w) ? R.map(w2w, w) : w)
const substUp = R.curry((h2h, w) => descend(h2h, descend(substUp(h2h), w)))

export const transform = R.curry((w2w, w) => w2w(substUp(w2w, w)))

export const rewrite = R.curry(
  (w2wO, w) =>
    transform(w0 => {const w1 = w2wO(w0)
                     if (R.equals(w0, w1))
                       return w0
                     else
                       return rewrite(w2wO, w1)
                    },
              w))
Esempio n. 27
0
import { curry, find, propEq } from 'ramda'
import { toJS } from 'mobx'

// findById<T> :: number -> T[] -> Nullable T
export const findById = curry((id, xs) =>
  find(propEq('id', id), xs)
)

export const trace = (msg) => (x) => {
  console.log(msg, toJS(x))
  return x
}
Esempio n. 28
0
  // ex1 :: Number -> Number -> Maybe Number
  ex1 = (x,y) => undefined


//-- Exercise 2 -------------------------------------------------------
// Now write a function that takes 2 Maybe's and adds them. Use `liftA2` instead of `ap`.
const
  // ex2 :: Maybe Number -> Maybe Number -> Maybe Number
  ex2 = undefined;


//-- Exercise 3 -------------------------------------------------------
// Run both `getPost(n)` and `getComments(n)` then render the page with both. (the n arg is arbitrary)
const
  makeComments = reduce((acc, {body}) => `${acc}<li>${body}</li>`, ""),
  render       = curry((p, cs) => `<div>${p.title}</div>${makeComments(cs)}`);

// ex3 :: Task Error HTML
const ex3 = undefined;


//-- Exercise 4 -------------------------------------------------------
// Write an IO that gets both player1 and player2 from the cache and starts the game
const
  localStorage = {player1: "toby", player2: "sally"},
  getCache     = x => new IO(() => localStorage[x]),
  game         = curry((p1, p2) => `${p1} vs ${p2}`);

// ex4 :: IO String
const ex4 = undefined;
Esempio n. 29
0
                'X-CSRF-Token': '3sWd2db2sWKsrgxQwuVYbmmbuqRTD2yq/XPWwf4pwQY=',
                'Accept-Language': 'en-US,en;q=0.8,pl;q=0.6,ru;q=0.4,fr;q=0.2',
                'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36',
                'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01',
                'Referer': 'https://www.siepomaga.pl/emil',
                'X-Requested-With': 'XMLHttpRequest',
                'Connection': 'keep-alive'
            }
        });
    },
    regexps = {
        date: "date\\\\\\'>([^<]+)<",
        donor: "name\\\\\\'>([^<]+)\\\\n<",
        amount: "amount\\\\\\'>[^>]+>([^(zł\\ )]+)"
    },
    fetchFirstGroup = _.curry((regexp, source) => _.match(regexp, source)[1]),

    findAllFirstRegexpGroup = _.curry((regexp, source) => {

        return _.pipe(
            _.match(new RegExp(regexp, 'gi')),
            _.map(fetchFirstGroup(new RegExp(regexp, 'i')))
        )(source);
    }),

    rawPageToDonations = (rawPageBody) => {

        let data = _.mapObjIndexed(findAllFirstRegexpGroup(_.__, rawPageBody))(regexps);

        return _.pipe(
            _.values,
Esempio n. 30
0
/**
 * @name Split Rules
 * @description This module exposes functions
 *              related to the `/transactions/:transactionId/split_rules` path.
 *
 * @module splitRules
 **/

import { cond, has, curry, both } from 'ramda'

import routes from '../routes'
import request from '../request'

const findAll = curry((opts, body) =>
  request.get(opts, routes.splitRules.findAll(body.transactionId), {})
)

const findOne = curry((opts, body) => {
  const { transactionId, id } = body
  return request.get(opts, routes.splitRules.find(transactionId, id), {})
})

/**
 * `GET /transactions/:transactionId/split_rules`
 * Makes a request to /transactions/:transactionId/split_rules or
 * to /transactions/:transactionId/split_rules/:id
 *
 * @param {Object} opts - An options params which
 *                      is usually already bound
 *                      by `connect` functions.
 *