const scoreUpper = scoreVal => R.compose( R.sum, R.filter(R.equals(scoreVal)) )
import R from 'ramda'; export const lensMatching = pred => toF => entities => { const index = R.findIndex(pred, entities); return R.map(entity => R.update(index, entity, entities), toF(entities[index])); }; export const lensById = R.compose(lensMatching, R.propEq('id')); export const hasSameId = R.eqProps('id'); export const rejectById = (id, arr) => R.reject(hasSameId({ id }), arr); export const strLen = R.curry(str => !str ? 0 : str.length); export const isStringEmpty = R.compose(R.isEmpty, R.trim); export const isNilOrEmpty = R.either(R.isNil, isStringEmpty); export const notNilOrEmpty = R.compose(R.not, isNilOrEmpty);
var m = require('mori'), r = require('ramda'), proton = require('../lib/proton'), atom = require('../lib/atom'); function is(type, thing) { return typeof(thing) === type; } 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):
S.maybe( messages.concat({ message: "You did not pass the edX course." }), run => messages.concat({ message: `You did not pass the edX course, but you can re-enroll. ${courseStartMessage( run )}${enrollmentDateMessage(run)}`, action: courseAction(run, COURSE_ACTION_REENROLL) }), futureEnrollableRun(course) ) ) } return messages.length === 0 ? S.Nothing : S.Just(messages) } const formatMessages = R.addIndex(R.map)(formatMessage) const wrapMessages = messages => ( <div className="course-status-messages">{messages}</div> ) const StatusMessages = R.compose( S.maybe(null, wrapMessages), S.map(formatMessages), calculateMessages ) export default StatusMessages
'use strict'; const fs = require('fs'); const path = require('path'); const R = require('ramda'); const isMDFile = R.compose(R.equals('.md'), path.extname); exports.findMDFile = function findMDFile(fileName, shallow) { const filePaths = Array.isArray(fileName) ? fileName : [fileName]; let mds = []; R.forEach((filePath) => { const stat = fs.statSync(filePath); if (stat.isFile() && isMDFile(filePath)) { mds.push(filePath); } if (stat.isDirectory()) { const indexFile = path.join(filePath, 'index.md'); let hasIndexFile = false; try { hasIndexFile = fs.statSync(indexFile).isFile(); } catch (e) {} if (shallow && hasIndexFile) { mds.push(indexFile); } else { const subFiles = fs.readdirSync(filePath) .map((subFile) => path.join(filePath, subFile)); mds = mds.concat(findMDFile(subFiles, shallow)); } }
const loadInstrumentBuffers = (context, instruments) => compose( traverse(Task.of, getBufferFromInstrument(context)), filter(filterInstrumentsWithSounds), )(instruments)
describe('Chapter 5', function () { // Functional Libraries used in this chapter const _ = require('lodash'); const R = require('ramda'); // Monads/functors used const Wrapper = require('../../model/Wrapper.js').Wrapper; const wrap = require('../../model/Wrapper.js').wrap; const empty = require('../../model/Empty.js').empty; const Maybe = require('../../model/monad/Maybe.js').Maybe; const Either = require('../../model/monad/Either.js').Either; const IO = require('../../model/monad/IO.js').IO; // Models used const Student = require('../../model/Student.js').Student; const Address = require('../../model/Address.js').Address; const Person = require('../../model/Person.js').Person; test("Simple Wrapper test", function () { const wrappedValue = wrap('Get Functional'); expect(wrappedValue.map(R.identity)).toEqual('Get Functional'); //-> 'Get Functional' }); test("Simple functor test", function () { const plus = R.curry((a, b) => a + b); const plus3 = plus(3); const plus10 = plus(10); const two = wrap(2); const five = two.fmap(plus3); //-> Wrapper(5) expect(five.map(R.identity)).toEqual(5); //-> 5 expect(two.fmap(plus3).fmap(plus10).map(R.identity)).toEqual(15); //-> Wrapper(15) }); test("Simple find with wrapper", function () { // Use helper DB created in chapter 1 const db = require('../../ch01/helper').db; const find = R.curry((db, id) => db.find(id)); const findStudent = R.curry((db, ssn) => { return wrap(find(db, ssn)); }); const getAddress = (student) => { return wrap(student.fmap(R.prop('firstname'))); }; const studentAddress = R.compose( getAddress, findStudent(db) ); expect(studentAddress('444-44-4444')).toEqual(wrap(wrap('Alonzo'))); }); test("Simple empty container", function () { const isEven = (n) => Number.isFinite(n) && (n % 2 == 0); const half = (val) => isEven(val) ? wrap(val / 2) : empty(); expect(half(4)).toEqual(wrap(2)); //-> Wrapper(2) expect(half(3)).toEqual(empty()); //-> Empty }); test("Simple empty container", function () { const WrapperMonad = require('../../model/monad/Wrapper.js').Wrapper; let result = WrapperMonad.of('Hello Monads!') .map(R.toUpper) .map(R.identity); //-> Wrapper('HELLO MONADS!') expect(result).toEqual(new WrapperMonad('HELLO MONADS!')); }); test("Simple Maybe Test", function () { let result = Maybe.of('Hello Maybe!').map(R.toUpper); expect(result).toEqual(Maybe.of('HELLO MAYBE!')); const Nothing = require('../../model/monad/Maybe.js').Nothing; result = Maybe.fromNullable(null); expect(result).toEqual(new Nothing(null)); }); test("Maybe to extract a nested property in object graph", function () { let address = new Address('US'); let student = new Student('444-44-4444', 'Joe', 'Smith', 'Harvard', 1960, address); const getCountry = (student) => student .map(R.prop('address')) .map(R.prop('country')) .getOrElse('Country does not exist!'); expect(getCountry(Maybe.fromNullable(student))).toEqual(address.country); }); test("Maybe to extract a missing nested property in object graph", function () { let student = new Student('444-44-4444', 'Joe', 'Smith', 'Harvard', 1960, null); const getCountry = (student) => student .map(R.prop('address')) .map(R.prop('country')) .getOrElse('Country does not exist!'); expect(getCountry(Maybe.fromNullable(student))).toEqual('Country does not exist!'); }); test("Simple Either monad test", function () { // Use helper DB created in chapter 1 const db = require('../../ch01/helper').db; const find = R.curry((db, id) => db.find(id)); const safeFindObject = R.curry(function (db, id) { const obj = find(db, id); if (obj) { return Either.of(obj); } return Either.left(`Object not found with ID: ${id}`); }); const findStudent = safeFindObject(db); let result = findStudent('444-44-4444').getOrElse(new Student()); expect(result).toEqual(new Person('444-44-4444', 'Alonzo', 'Church')); result = findStudent('xxx-xx-xxxx'); expect(result).toEqual(Either.left(`Object not found with ID: xxx-xx-xxxx`)); expect(() => { console.log(result.value); }).toThrow(TypeError); }); // Common code used in the next unit tests // Use helper DB created in chapter 1 const db = require('../../ch01/helper').db; // validLength :: Number, String -> Boolean const validLength = (len, str) => str.length === len; const find = R.curry((db, id) => db.find(id)); // safeFindObject :: Store, string -> Either(Object) const safeFindObject = R.curry((db, id) => { const val = find(db, id); return val ? Either.right(val) : Either.left(`Object not found with ID: ${id}`); }); // checkLengthSsn :: String -> Either(String) const checkLengthSsn = ssn => validLength(9, ssn) ? Either.right(ssn) : Either.left('invalid SSN'); // finStudent :: String -> Either(Student) const findStudent = safeFindObject(db); // csv :: Array => String const csv = arr => arr.join(','); const trim = (str) => str.replace(/^\s*|\s*$/g, ''); const normalize = (str) => str.replace(/\-/g, ''); const cleanInput = R.compose(normalize, trim); test("Using Either in show Student", function () { const showStudent = (ssn) => Maybe.fromNullable(ssn) .map(cleanInput) .chain(checkLengthSsn) .chain(findStudent) .map(R.props(['ssn', 'firstname', 'lastname'])) .map(csv) .map(R.tap(console.log)); //-> Using R.tap to simulate the side effect (in the book we write to the DOM) let result = showStudent('444-44-4444').getOrElse('Student not found!') expect(result).toEqual('444-44-4444,Alonzo,Church'); result = showStudent('xxx-xx-xxxx').getOrElse('Student not found!'); expect(result).toEqual('Student not found!'); }); test("Monads as programmable commas", function () { // map :: (ObjectA -> ObjectB), Monad -> Monad[ObjectB] const map = R.curry((f, container) => container.map(f)); // chain :: (ObjectA -> ObjectB), M -> ObjectB const chain = R.curry((f, container) => container.chain(f)); const lift = R.curry((f, obj) => Maybe.fromNullable(f(obj))); const trace = R.curry((msg, obj) => console.log(msg)); const showStudent = R.compose( R.tap(trace('Student printed to the console')), map(R.tap(console.log)), //-> Using R.tap to simulate the side effect (in the book we write to the DOM) R.tap(trace('Student info converted to CSV')), map(csv), map(R.props(['ssn', 'firstname', 'lastname'])), R.tap(trace('Record fetched successfully!')), chain(findStudent), R.tap(trace('Input was valid')), chain(checkLengthSsn), lift(cleanInput) ); let result = showStudent('444-44-4444').getOrElse('Student not found!'); expect(result).toEqual('444-44-4444,Alonzo,Church'); }); test("Complete showStudent program", function () { // map :: (ObjectA -> ObjectB), Monad -> Monad[ObjectB] const map = R.curry((f, container) => container.map(f)); // chain :: (ObjectA -> ObjectB), M -> ObjectB const chain = R.curry((f, container) => container.chain(f)); const lift = R.curry((f, obj) => Maybe.fromNullable(f(obj))); const liftIO = function (val) { return IO.of(val); }; // For unit testing purposes, this could be replaced with R.tap const append = R.curry(function (elementId, info) { console.log('Simulating effect. Appending: ' + info) return info; }); const getOrElse = R.curry((message, container) => container.getOrElse(message)); const showStudent = R.compose( map(append('#student-info')), liftIO, getOrElse('unable to find student'), map(csv), map(R.props(['ssn', 'firstname', 'lastname'])), chain(findStudent), chain(checkLengthSsn), lift(cleanInput) ); let result = showStudent('444-44-4444').run(); expect(result).toEqual('444-44-4444,Alonzo,Church'); let result2 = showStudent('xxx-xx-xxxx').run(); expect(result2).toEqual('unable to find student'); }); });
var R = require('ramda'); var Task = require('data.task'); var Maybe = require('data.maybe'); var p = function () { return new Promise(function (resolve, reject) { setTimeout(function () { resolve('got data'); }, 300) }) }; //p().then(console.log); var g = R.compose(Task.of, p); g().fork(console.error, console.log);
var getVal = x => x && x.value // noNils :: [a] -> [a] var noNils = R.reject(R.isNil); // tap :: x -> State(x, state) var of = R.curry((x,_) => State.of(x)); var tail = ns => of(R.tail(ns)); // isTextNode :: node -> Boolean var isTextNode = R.propEq('type','Text'); // isntTextNode :: node -> Boolean var isntTextNode = R.compose( R.not, isTextNode ); // isTemplate :: [node] => Boolean var isTemplate = R.pathEq([0,'name'], 'template'); // gtext :: [node] => [String] var gtext = R.compose( R.map(R.prop('content')), R.filter( isTextNode ) ); // globals :: [node] => State([node], state) var globals = ns => State.write(s => [R.filter( isntTextNode, ns ), R.over(R.lensProp('globals'), R.concat(gtext(ns)), s)]); // isDynText :; String -> Boolean var isDynText = R.test(/\{[^{}]+\}/); // isDynamicAttr :: Obj -> Boolean isDynamicAttr = R.compose( isDynText, R.prop('value'));
<Route path={sitePaths.entreprise.statutJuridique.autoEntrepreneur} component={withAnimation(AutoEntrepreneur)} /> <Route path={sitePaths.entreprise.statutJuridique.multipleAssociates} component={withAnimation(NumberOfAssociate)} /> <Route path={sitePaths.entreprise.statutJuridique.minorityDirector} component={withAnimation(MinorityDirector)} /> <Route path={sitePaths.entreprise.statutJuridique.liste} component={withAnimation(PickLegalStatus)} /> </Switch> </Animate.fromBottom> </> ) } export default compose( connect(state => ({ companyStatusChoice: state.inFranceApp.companyStatusChoice, existingCompany: state.inFranceApp.existingCompanyDetails })), withTranslation(), withSitePaths )(CreateMyCompany)
import cx from 'classnames'; import { lenses, getId } from 'plio-util'; import { view, propEq, find, either, compose } from 'ramda'; import { StandardTypes } from '../../../../../../share/collections'; import { sortArrayByTitlePrefix } from '../../../../../../api/helpers'; import { DefaultStandardTypes } from '../../../../../../share/constants'; // this will only work if the organization hasn't removed/changed // the default Standard operating procedure type const getDefaultType = find(propEq( 'titlePrefix', DefaultStandardTypes.STANDARD_OPERATING_PROCEDURE.title, )); const getDefaultTypeId = either( compose(getId, getDefaultType), view(lenses.head._id), ); Template.ESType.viewmodel({ share: 'standard', mixin: ['organization', 'collapsing', 'standard'], typeId: '', autorun() { // to fix bug wich randomly calls method if (this.typeId() !== this.templateInstance.data.typeId) { Tracker.nonreactive(() => this.update()); } }, onCreated() { if (!this.typeId()) {
var accounting = require('accounting'); // Example Data var CARS = [ {name: "Ferrari FF", horsepower: 660, dollar_value: 700000, in_stock: true}, {name: "Spyker C12 Zagato", horsepower: 650, dollar_value: 648000, in_stock: false}, {name: "Jaguar XKR-S", horsepower: 550, dollar_value: 132000, in_stock: false}, {name: "Audi R8", horsepower: 525, dollar_value: 114200, in_stock: false}, {name: "Aston Martin One-77", horsepower: 750, dollar_value: 1850000, in_stock: true}, {name: "Pagani Huayra", horsepower: 700, dollar_value: 1300000, in_stock: false} ]; // Exercise 1: // ============ // use _.compose() to rewrite the function below. Hint: _.prop() is curried. var isLastInStock = _.compose(_.prop('in_stock'), _.last) // Exercise 2: // ============ // use _.compose(), _.prop() and _.head() to retrieve the name of the first car 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:
byType: function(type) { return R.compose(children.map, children.filter(type)); },
var Maybe = require('./maybe_functor'), helpers = require('./functor_helpers'), fmap = helpers.fmap; /* * Identity Functor Examples */ var add1 = fmap(R.add(1)); var mapHead = fmap(R.head); /* * Maybe Functor Examples */ var maybeNameStartsWith = R.compose(fmap(R.head), Maybe, R.prop('name')); var maybeParseInt = R.compose(fmap(parseInt), Maybe); /* * Either Functor Examples */ var eitherCheckIfUserIsActive = function(user) { return user.active ? Either.Right(user) : Either.Left('Your account is not active'); }; var welcomeUser = R.compose(R.add('Welcome '), R.prop('name')); var eitherGrantAccess = R.compose(fmap(welcomeUser), eitherCheckIfUserIsActive); var eitherUserNameIsLargerThan3CharsValidator = function(x) { return x.length > 3 ? Either.Right(x) : Either.Left('Need length greater than 3'); };
import { compose, lensProp, over } from 'ramda' export default compose(over, lensProp)
var elemify = (str, node, uid) => R.compose( R.over( R.lensProp('uid'), R.inc) , R.over( bodyL, R.append(str)) , R.over( R.lensProp('statics'), R.compose(noNils, R.append(defStatAttrs(node, uid)))) );
const duration = buffer.duration totalDuration += duration return { buffer, startTime, duration, volume: 1, } }) return getBufferFromAudioTemplate(audioTemplate, totalDuration) } // renderAudioPlaylistToBuffer :: [audioPlaylistItem] -> Task [audioBuffer] const renderAudioPlaylistItemToBuffer = compose( chain(combineAudioBuffers), traverse(Task.of, renderBuffer), ) // getPitchPlaybackRatio :: Integer -> Integer const getPitchPlaybackRatio = (pitchAmount) => { const pitchIsPositive = pitchAmount > 0 const negAmount = pitchIsPositive ? pitchAmount * -1 : pitchAmount const val = 1 / Math.abs((negAmount / 1200) - 1) return pitchIsPositive ? 1 / val : val } const playSound = (context, buffer, time, duration, volume, pitchAmount = 0, fadeInDuration = 0, fadeOutDuration = 0) => { if (!buffer) return const source = context.createBufferSource()
var getAttr = (name,attrs) => R.compose( getVal, R.find(R.propEq('name',name)))(attrs);
// Rename an objects keys and remove unknown keys. const renameKeys = curry((keysMap, obj) => reduce((acc, key) => { const ret = acc; if (obj[key]) { ret[keysMap[key] || key] = obj[key]; } return ret; }, {}, keys(keysMap))); // Rename an objects OAuth keys. const renameOAuthKeys = renameKeys(OAUTH_KEYS); // Prepend the method and url to the base string. const prependRequest = pipe( adjust(toUpper, 0), adjust(compose(concat(__, '&'), encode), 1), join('&'), concat, ); // Merge 2 objects into a given object. const mergeParams = compose(merge, merge); // Create an OAuth 1.0 signature. export default ({ url, consumerKey, consumerSecret, oauthToken = '', oauthSecret = '', params = {},
const extractFirstOf = keysOrPaths => R.pipe( R.of, R.ap(R.map(extract, keysOrPaths)), R.find(R.compose(R.not, R.isEmpty)), R.ifElse(R.identity, R.identity, R.always([])), )
d'achats d'équipement professionnel auprès de fournisseurs, etc. </T> </p> </> )} <p className="ui__ answer-group" style={{ justifyContent: 'space-between' }}> <Link to={sitePaths.entreprise.index} className="ui__ simple skip button left"> ← <T k="après.actions.retour">Démarche de création</T> </Link> <Link to={sitePaths.sécuritéSociale.index} className="ui__ plain button"> <T k="après.actions.avance">Estimez vos cotisations </T>→ </Link> </p> </Animate.fromBottom> ) } export default (compose( connect(state => ({ companyStatusChoice: state.inFranceApp.companyStatusChoice })), withTranslation(), withSitePaths )(AfterRegistration): React$ComponentType<OwnProps>)
// ========== // Use safeProp and map/join or chain to safely get the street name when given a user var safeProp = _.curry(function (x, o) { return Maybe.of(o[x]); }); var user = { id: 2, name: "albert", address: { street: { number: 22, name: 'Walnut St' } } }; var ex1 = _.compose(chain(safeProp('name')), chain(safeProp('street')), safeProp('address')); // Exercise 2 // ========== // Use getFile to get the filename, remove the directory so it's just the file, then purely log it. var getFile = function() { return new IO(function(){ return __filename; }); } var pureLog = function(x) { return new IO(function(){ console.log(x); return 'logged ' + x; // for testing w/o mocks });
{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));
const BaseFactory = (bucket) => R.compose( R.fromPairs , R.map((method) => [ method, callDriverMethod(method, bucket) ]) )(METHODS)
FROM pos_data WHERE store='DK130' AND starttime BETWEEN ? AND ?; `; const parseParams = (params) => { if (params.time) { return R.evolve({time: D.parse}, params); } return R.assoc('time', new Date(), params); }; const prepareValues = (params) => [ D.sub('minutes', 5, params.time), params.time, D.sub('minutes', 5, params.time), params.time, ]; const buildQueryValues = R.compose((x) => Promise.resolve(x), prepareValues, parseParams); const getConversion = R.composeP( (data) => data[0] / data[1], R.head, log('results'), db.safeQuery(CURRENT_CONVERSION_QUERY), log('stuff'), buildQueryValues ); module.exports = getConversion;
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,
"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); }
import {apply, reduce, compose, map} from 'ramda'; import handleOptions, {genExpect} from '../utils/handleOptions'; import {addDir} from '../utils/fs'; import {hasParents} from '../utils/validations'; import {toPath} from '../utils/pathUtils'; const noParentError = target => `mkdir: cannot create directory ${target}: No such file or directory`; const expectParent = genExpect(hasParents, noParentError); const addDirCheckParent = compose(apply(addDir), expectParent); const options = { handlers: { none: addDirCheckParent, p: addDir, }, fulls: { parent: 'p', }, }; const mkdir = (args, self) => { const {fileSystem, currentPath} = self.state; const {targets} = args; const mapToPath = map(toPath(currentPath)); const paths = mapToPath(targets); const newFs = reduce(
var getAnimalsByPage = function(pageNumber, pageSize) { return getFlatAnimalsByPage(pageNumber, pageSize).chain(R.compose(R.traverse(Task.of, R.identity), R.map(animalFromFlatAnimal))) }
const totalKinds = reducer => ofAKind => R.compose( R.reduce(reducer, 0), R.map(n => parseInt(n)*ofAKind), diceWithAtleast(ofAKind) )