Example #1
0
const expectArgumentError = (code, argumentName, errors) => {
  expectToFindErrorCode(code, errors);
  return expect(R.map(({ argument }) => argument, errors)).to.include(argumentName);
};
Example #2
0
const BIKE_TYPES = {
    2: BIKE_TYPE_NORMAL,
    3: BIKE_TYPE_ELECTRIC,
    4: BIKE_TYPE_CHILD_SEAT,
    5: BIKE_TYPE_BABY,
};

const setBikeType = bike => ({
    ...bike,
    type: propOr(BIKE_TYPE_NORMAL, propOr(2, 'id', bike), BIKE_TYPES),
});

const lowerCaseKeys = compose(
    fromPairs,
    map(
        adjust(toLower, 0),
    ),
    toPairs
);

const setBikes = map(
    compose(
        pick(['count', 'type', 'name']),
        setBikeType,
        lowerCaseKeys,
        obj => merge(path(['VehicleType'], obj), obj),
    )
);

const cleanData = compose(
    filter(path(['active'])),
Example #3
0
const renderArticles = (articles) => {
  $('#container').html('');
  const renderArticle = renderTemplate($("#article-template").html());
  _.map(renderArticle, datastore.articles);
}
var getAnimalsByPage = function(pageNumber, pageSize) {
	return getFlatAnimalsByPage(pageNumber, pageSize).chain(R.compose(R.traverse(Task.of, R.identity), R.map(animalFromFlatAnimal)))
}
// Exercise 1:
// ============
var isLastInStock = _.compose(_.prop('in_stock'), _.last)

// Exercise 2:
// ============
var nameOfFirstCar = _.compose(_.prop('name'), _.head)


// Exercise 3:
// ============
// Use the helper function _average to refactor averageDollarValue as a composition

var _average = function(xs) { return reduce(add, 0, xs) / xs.length; }; // <- leave be

var averageDollarValue = _.compose(_average, _.map(_.prop('dollar_value')))


// Exercise 4:
// ============
// Write a function: sanitizeNames() using compose that returns a list of lowercase and underscored names: e.g: sanitizeNames(["Hello World"]) //=> ["hello_world"].

var _underscore = replace(/\W+/g, '_'); //<-- leave this alone and use to sanitize

var sanitizeNames = _.map(_.compose(_underscore, toLowerCase, _.prop('name')))


// Bonus 1:
// ============
// Refactor availablePrices with compose.
Example #6
0
function resolveFile(fullpath, buffer) {
    const dirnames = fullpath.split('/').splice(0, fullpath.split('/').length - 1)
    const filename = fullpath.split('/').splice(-1)[0]

    dirpaths = ramda.scan(
        (a, b) => ramda.append(b, a),
        [],
        dirnames
    )

    dirpaths = ramda.map(
        d => d.join('/'),
        dirpaths
    ).filter(
        path => path.length != 0
    )

    const promises = ramda.map(
        path => {
            return () => {
                return (new Promise(
                    (res, rej) => {
                        access(
                            path,
                            fs.W_OK,
                            err => err ? rej(err) : res(path)
                        )
                    }
                )).catch(err => {
                    return new Promise(
                        (res, rej) => {
                            mkdir(
                                path,
                                err => err ? rej(err) : res(path)
                            )
                        }
                    )
                })
            }
        },
        dirpaths
    )

    var i = 0
    const filePromise = ramda.reduce(
        (a, b) => {
            return a.then(() => b())
        },
        Promise.resolve(),
        promises
    ).then(() => {
        return new Promise((res, rej) => {
            writeFile(
                fullpath,
                buffer,
                err => err ? rej(err) : res({ location: fullpath })
            )
        }).catch(err => console.log(err))
    })

    return filePromise
}
Example #7
0
}

var sortedKeys = r.compose(r.sort, r.keys);
var derefProp = r.compose(proton.deref, r.prop);
var pathProp = r.compose(proton.path, r.prop);

module.exports = {
  proton() {
    return this.props.s;
  },
  shouldComponentUpdate(nextProps, nextState) {
    var next = nextProps.s,
        actual = this.proton();
    switch(true) {
    case Array.isArray(actual) && Array.isArray(next):
      return !(r.all(r.apply(m.equals), r.zip(r.map(proton.path, actual),
                                              r.map(proton.path, next))) &&
               r.all(r.apply(m.equals), r.zip(r.map(proton.deref, actual),
                                              r.map(proton.deref, next))));
    case proton.isProton(actual) && proton.isProton(next):

      return !(m.equals(proton.path(actual), proton.path(next)) &&
               m.equals(proton.deref(next), proton.deref(actual)));
    case is('object', actual) && is('object', next):
      return !(r.all(r.apply(m.equals),
                     r.zip(r.map(pathProp, sortedKeys(actual)),
                           r.map(pathProp, sortedKeys(next)))) &&
               r.all(r.apply(m.equals),
                    r.zip(r.map(derefProp, sortedKeys(actual)),
                          r.map(derefProp, sortedKeys(next)))));
    default:
Example #8
0
export default headers => (
  <div>
    {map(makeRow, toPairs(headers))}
  </div>
)
let cheerio = require('cheerio'),
    R = require('ramda');

function splitLines(text) {
  return text.split("\n");
}

let trimWhitespace = R.map(x => x.trim());

let textFromSelector = R.curry(function(selector, html) {
  return cheerio.load(html)(selector).text();
});

module.exports = R.curry(function parse(selector, html) {
  return R.pipe(textFromSelector(selector), splitLines, trimWhitespace)(html);
});
Example #10
0
const mapNoticon = key => propOr( 'star', key, {
	'\uf814': 'mention',
	'\uf300': 'comment',
	'\uf801': 'add',
	'\uf455': 'info',
	'\uf470': 'lock',
	'\uf806': 'stats',
	'\uf805': 'reblog',
	'\uf408': 'star',
	'\uf804': 'trophy',
	'\uf414': 'warning'
} );

const avatar = prop( 'icon' );
const body = compose( map( parseBlock ), prop( 'body' ) );
const hasReplied = compose( has( 'reply_comment' ), propOr( {}, 'ids' ), propOr( {}, 'meta' ) );
const header = compose( defaultTo( [] ), head, map( parseBlock ), reject( isNil ), of, head, propOr( [], 'header' ) );
const headerExcerpt = compose( nth( 1 ), propOr( [], 'header' ) );
const icon = compose( mapNoticon, prop( 'noticon' ) );
const id = prop( 'id' );
const read = prop( 'read' );
const subject = compose( head, map( parseBlock ), of, head, prop( 'subject' ) );
const subjectExcerpt = compose( nth( 1 ), propOr( [], 'subject' ) );
const timestamp = compose( Date.parse, prop( 'timestamp' ) );
const title = prop( 'title' );
const type = prop( 'type' );

const propertyGetters = {
	avatar,
	body,
var fs = require('fs'),
    R = require('ramda');

var jsonData = require('./AllSets.json');

var newSets = R.map(edition => {
    var cards = R.zipObj(R.map(x => x.name.toLowerCase(), jsonData[edition.code].cards), R.map(x => x, jsonData[edition.code].cards))

    var keys = R.keys(cards);
    var values = R.values(cards);

    var names = R.map(x => x.toString().toLowerCase(), keys);
    names = R.map(x => R.replace(/[\/]/g, '%%', x.toString()), names);
    names = R.map(x => R.replace(/[\.]/g, '@@', x.toString()), names);

    var cardsFormatted = R.zipObj(names, values);
    edition.cards = cardsFormatted;

    return edition;

}, jsonData)


fs.writeFile('newSets.json', JSON.stringify(newSets));
console.log('done');

// editions mardcardinfo map
/*keys.forEach(function(element) {
    values.push(jsonData[element].magicCardsInfoCode)
}, this);
*/
import React from 'react'
import {
  flatten,
  map,
  mergeAll,
  pipe,
  split
} from 'ramda'

const splitVector = pipe(
  split(' '),
  map(split(',')),
  flatten
)

export default React.createClass({
  displayName: 'TreeNodeAttributeTextbox',
  propTypes: {
    attributeName: React.PropTypes.string.isRequired,
    index: React.PropTypes.number.isRequired,
    owner: React.PropTypes.object.isRequired,
    style: React.PropTypes.object
  },
  handleChangeEvent: function (event) {
    const {attributeName, index, owner} = this.props
    const oldVector = splitVector(owner.getAttribute(attributeName))

    oldVector[index] = event.currentTarget.value
    owner.setAttribute(attributeName, oldVector.join(' '))

    this.forceUpdate()
import globby from 'globby';
import R from 'ramda';
import { contractP } from './utils/contract';
import Promise from 'pinkie-promise';
import binded from 'binded';

const { resolve } = binded(Promise);

// fs :: String -> Promise Array[String]
const fs = R.unary(R.pipeP(resolve,
  contractP('path', String),
  path => globby(['**/*.js', '!node_modules/**'], { cwd: path }),
  R.map(R.concat('./'))));

export default fs;
Example #14
0
import { createSelector } from 'reselect';
import { map } from 'ramda';

import { getRiskTypes } from './state';

const selector = map(({ _id, title }) => ({
  value: _id,
  text: title,
}));

export default createSelector(getRiskTypes, selector);
Example #15
0
 $('feed > entry').each((i, element) => {
   if (!R.contains(id, R.map(x => x.id, reviews))) {
     reviews.push(this.parse($(element)));
   }
 });
Example #16
0
           {name: "Utu", dad: "Panu", mom: "Martta"},
           {name: "Kaarna", dad: "Panu", mom: "Riikka"},
           {name: "Liekki", dad: "Panu", mom: "Henna"}];

const crossmap = ls1 => _.chain(e2 => _.map(e => [e, e2], ls1));
const cartesian_square = ls => crossmap(ls)(ls);

const pair_has_common_parent =
	_.apply(_.either(_.eqBy(_.prop('mom')), _.eqBy(_.prop('dad'))));

const sibling_pairs = people =>
	_.map(pair => _.map(_.prop('name'), pair),
	  _.filter(pair_has_common_parent,
	    _.filter(_.apply(_.complement(_.equals)),
	      cartesian_square(people))));

console.log(sibling_pairs(data));

// You can use the currying nature of iterators to write even more
// cryptic code, yay.

const sibling_pairs2 = 
	_.compose(
		_.map(_.map(_.prop('name'))),
		_.filter(pair_has_common_parent),
		_.filter(_.apply(_.complement(_.equals))),
		cartesian_square);

console.log(sibling_pairs2(data));

'use strict'

var R = require('ramda')

module.exports = R.map(R.propOr('', 'type'))
Example #18
0
const crossmap = ls1 => _.chain(e2 => _.map(e => [e, e2], ls1));
Example #19
0
"use strict";

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var R = require("ramda");
var expr = require("./expression");

var events = R.compose(R.fromPairs, R.map(function (n) {
  return [n, true];
}))(['onClick', 'onDoubleClick', 'onMouseDown', 'onMouseUp', 'onMouseEnter', 'onMouseLeave', 'onMouseOver', 'onMouseOut', 'onInput', 'onCheck', 'onSubmit', 'onSubmitOptions', 'onBlur', 'onFocus']);

function count(what, where) {
  var m = where.match(new RegExp(what, "g"));
  return m ? m.length : 0;
}

function missingCloseBracket(data) {
  throw "Missing '}' in value for attribute '" + data.name + "'";
}

function reduceAttrs(data, attr) {
  var _attr = _slicedToArray(attr, 2);

  var name = _attr[0];
  var value = _attr[1];


  var depth = data.depth + count("{", value) - count("}", value);
  if (depth < 0) {
    throw "Extra '}' in '" + value + "' for attribute " + (name || data.name);
  }
Example #20
0
const sibling_pairs = people =>
	_.map(pair => _.map(_.prop('name'), pair),
	  _.filter(pair_has_common_parent,
	    _.filter(_.apply(_.complement(_.equals)),
	      cartesian_square(people))));
Example #21
0
  ]);
};

var $$typeDropdown = $$dropdown({
  defaultText: '请选择发票类型',
  onchange(invoiceTypeId) {
    $$obj.patch({
      invoiceTypeId,
      invoiceType: R.find(R.propEq('id', invoiceTypeId))($$invoiceTypes.val()),
      amount: '',
    });
    $$storeOrders.val([]);
  },
  $$options: $$invoiceTypes.trans(R.map(function (it) {
    return {
      value: it.id,
      text: it.name,
    };
  })),
  $$value: $$obj.trans(R.prop('invoiceTypeId')),
});

var $$accountTermDropdown = $$dropdown({
  defaultText: '请选择会计账期',
  $$options: $$accountTerms.trans(R.map(it => ({
    value: it.id,
    text: it.name + (it.closed? '(已关闭)': ''),
  }))),
  $$value: $$obj.trans(R.prop('accountTermId')),
  onchange(accountTermId) {
    $$obj.patch({ accountTermId });
  },
Example #22
0
	_.map(pair => _.map(_.prop('name'), pair),
var saveObjectsAndIdsFor = function(collection, objects){
	var saveObjectAndId = saveObjectAndIdFor(collection)
	var saveObjects = R.map(saveObjectAndId, objects)
	return R.traverse(Task.of, R.identity, saveObjects)
}
export const lensMatching = pred => toF => entities => {
    const index = R.findIndex(pred, entities);
    return R.map(entity => R.update(index, entity, entities), toF(entities[index]));
};
var log = require('./log');
var R = require('ramda');

var people = [
    {firstName: 'Scott', age: 50},
    {firstName: 'Anthony', age: 40},
    {firstName: 'Jim', age:25},
    {firstName: 'Mike', age: 20}
];

var byFirstName = R.compose(R.toLower, R.prop('firstName'));
var byAge = R.prop('age');


var showUsers = R.pipe(
    R.map(JSON.stringify),
    R.join('\n'),
    log
);


showUsers(R.sortBy(byFirstName, people));
showUsers(R.sortBy(byAge, people));
Example #26
0
export const expectToFindErrorCode = (code, errors) => {
  return expect(R.map(extractCode, errors)).to.include(code);
};
Example #27
0
const topTrackInfo = ( track ) => {
  const title = getKey( null, [ 'name' ] )( track );
  const artist = getKey( null, [ 'artist', 'name' ] )( track );
  const playcount = getKey( null, [ 'playcount' ] )( track );
  const rank = getKey( null, [ '@attr', 'rank' ] )( track );
  return {
    title,
    artist,
    playcount,
    rank
  };
};

/* TRANSFORMS */

const transformRecentTracks = R.compose( R.map( recentTrackInfo ), getKeyRecentTracks );

const transformTopTracks = R.compose( R.map( topTrackInfo ), getKeyTopTracks );

const sortRecentTracks = ( tracks ) => {
  const sortByEpoch = R.pipe( R.sortBy( R.prop( 'epoch' ) ), R.reverse );
  const findActiveTrack = ( track ) => {
    if ( R.pathOr( false, [ 'active' ], track ) ) {
      return true;
    } else {
      return false;
    }
  };
  let active_track = R.filter( findActiveTrack, tracks );
  const sorted_tracks = ( () => {
    const sorted = sortByEpoch( tracks );
 content.compileResults(sourceGroupUrls).then(function(results){
     var fulfilledResults = R.map(function(result){
         return result.value;
     }, results);
     deferred.resolve(fulfilledResults);
 });
Example #29
0
const renderDeposits = (deposits) => {
  $('#container').html('');
  const renderDeposit = renderTemplate($("#deposit-template").html());
  _.map(renderDeposit, datastore.deposits);
}
Example #30
0
const BaseFactory = (bucket) => R.compose(
  R.fromPairs
, R.map((method) => [ method, callDriverMethod(method, bucket) ])
)(METHODS)