Example #1
0
const validations = state => [
  {
    error: "Todo must have a text description.",
    predicate: has("text")
  },
  {
    error: "Todo text must not be empty.",
    predicate: where({ text: complement(isEmpty) })
  },
  {
    error: "Todo text must be unique.",
    predicate: where({ text: flip(complement(contains))(pluck("text", state.todos)) })
  }
];
Example #2
0
export const checkInvalidNameChars = R.curry((key, label, profile) =>
  checkProp(
    key,
    `${label} must not contain comma, double quote, or greater than characters`,
    R.complement(R.test(INVALID_NAME_CHARS_REGEX)),
    profile
  )
Example #3
0
    const _parse = (tokens) => {
        // current :: TokenTuple
        let current = tokens.head()
        // rest :: List TokenTuple
        let rest = tokens.tail()

        // Util function for checking if it's a different token, finishing parsing
        // notAnotherToken :: Token -> Boolean
        let notAnotherToken = R.complement(
            R.anyPass([
                R.is(Option),
                R.is(Command),
                R.is(Path)
            ])
        )

        // isWordAndNotToken :: Token -> Boolean
        const isWordAndNotToken = R.allPass([
            R.is(Word),
            notAnotherToken,
        ])

        // extractAndTest :: TokenTuple -> Boolean
        const extractAndTest = R.compose(isWordAndNotToken, Tuple.snd)

        if (cont === true && extractAndTest(current)) {
            optionSet = optionSet.concat(List.of(current))

            return _parse(rest)
        } else {
            cont = false
            remaining = List.of(current).concat(rest)
        }
    }
function handleStatus(taskStatusData) {
	const statusDone = R.propEq('status', 'done');
	const statusNotNotStarted = R.complement(
		R.propEq('status', 'not started')
	);

	const completed = R.takeWhile(
		statusDone,
		taskStatusData.tool_status
	);
	const notCompleted = R.dropWhile(
		statusDone,
		taskStatusData.tool_status
	);
	const current = R.filter(
		statusNotNotStarted,
		notCompleted
	);
	const pending = R.dropWhile(
		statusNotNotStarted,
		notCompleted
	);

	return { completed, current, pending };
};
Example #5
0
export const checkLatin = R.curry((key, label, profile) =>
  checkProp(
    key,
    `${label} must be in Latin characters`,
    [R.complement(isNilOrEmptyString), R.test(CP1252_REGEX)],
    profile
  )
Example #6
0
function invokeFunction(symbolTable, fn, args) {
  var fun = evaluate(symbolTable, fn);
  var evaledArgs = () => args.map(evaluate.bind(null, symbolTable));
  var inSymbolTable = value => R.contains(value, R.values(symbolTable));
  var notInSymbolTable = R.complement(inSymbolTable);
  var isPureJSFunction = R.both(notInSymbolTable, isJsFunction);

  return R.cond([[isLambda, () => executeLambda(symbolTable, fun, args)], [isPureJSFunction, () => fun.apply(undefined, _toConsumableArray(evaledArgs()))], [isJsFunction, () => fun.apply(null, [symbolTable].concat(evaledArgs()))], [R.T, () => new Error("Error in invokeFunction")]])(fun);
}
Example #7
0
File: deep.js Project: do0g/deep
const deep = curry((callback, obj, path) => {
  if (is(Array, obj)) {
    return filter(compose(not, isEmpty), map(deep(callback, __, path), obj));
  }
  if (isPlainObject(obj)) {
    return mergeAll(filter(complement(isNil), map(iteratee(callback, path), toPairs(obj))));
  }
  return obj;
});
Example #8
0
const main = () => {
  const filename = process.argv[4]
  const clockDeviceName = process.argv[2]
  const messageDeviceName = process.argv[3]
  Console.log('Starting recording to', filename)
  const fileStream = fs.createWriteStream(filename)
  const stdin = RxNode.fromStream(process.stdin, 'end')
  stdin.finally(() => fileStream.end())

  const clockInput = new midi.input()
  clockInput.ignoreTypes(false, false, false)

  const messageInput = new midi.input()
  messageInput.ignoreTypes(false, false, false)

  const closePorts = () => {
    Console.log('Closing ports')
    clockInput.closePort()
    messageInput.closePort()
  }

  process.on('exit', closePorts)
  process.on('SIGINT', closePorts)
  process.on('uncaughtException', closePorts)

  const clockInputSubject = new Rx.Subject()
  clockInput.on('message', (deltaTime, message) => clockInputSubject.onNext([deltaTime, message]))
  const clock = clockInputSubject.filter(R.flip(R.contains)([ClockTick, ClockStart]))

  const messageInputSubject = new Rx.Subject()
  messageInput.on('message', (deltaTime, message) => messageInputSubject.onNext([deltaTime, message]))
  const messages = messageInputSubject.filter(R.complement(R.flip(R.contains)([ClockTick, ClockStart])))

  clockInput.openPort(getPortNumber(clockDeviceName))
  messageInput.openPort(getPortNumber(messageDeviceName))

  const position = clock.scan(([phrase, bar, beat, tick], message) => {
    if (R.equals(message, ClockStart)) {
      return [0,0,0,0]
    }

    const tickOverflow = tick === 23 ? 1 : 0
    tick = (tick + 1) % 24
    const beatOverflow = beat === 3 && tickOverflow ? 1 : 0
    beat = (beat + tickOverflow) % 4
    const barOverflow = bar === 3 && beatOverflow ? 1 : 0
    bar = (bar + beatOverflow) % 4
    phrase += barOverflow
    return [phrase, bar, beat, tick]
  }, [0, 0, 0, 0])

  messages.withLatestFrom(position, Array)
    .map(R.reverse)
    .map(JSON.stringify)
    .subscribe(serializedData => fileStream.write(serializedData + '\n'))
}
function detectStatus(obj) {
  const combined = obj.main + obj.sub;
  const isPrivate = R.test(/private/i);
  const isAccessible = R.both(R.test(/unavailable/i), R.complement(R.test(/sorry/i)));
  const isUnavailable = R.either(R.test(/not exist/i), R.both(R.test(/unavailable/i), R.test(/sorry/i)));

  return R.cond([
    [isPrivate, R.always('private')],
    [isAccessible, R.always('accessible')],
    [isUnavailable, R.always('unavailable')],
    [R.T, R.always('unknown')]
  ])(combined);
}
Example #10
0
export const checkMaxLength = R.curry((key, label, maxLength, profile) =>
  checkProp(
    key,
    `${label} must be no more than ${maxLength} characters`,
    [
      R.complement(isNilOrEmptyString),
      R.pipe(
        R.toString,
        R.prop("length"),
        R.lte(R.__, maxLength)
      )
    ],
    profile
  )
Example #11
0
export default function (name, paramTypes, func) {
	const variadicIndex = variadicParameterIndex(paramTypes);
	const isVariadic = variadicIndex !== -1;

	const subject = createSubject(name, paramTypes, func, isVariadic, variadicIndex);

	if (name) {
		paramTypes
			.filter(complement(isVectorType))
			.forEach(addMethod(name, variadicIndex, isVariadic, subject, paramTypes));
	}

	return subject;
}
Example #12
0
 render() {
   const messages = this.props.messages.filter(R.complement(R.isNil));
   if (!messages.length) {
     return null;
   }
   return (
     <div className="error-msg">
       <ul>
         {messages.map((message, i) => {
           return <li key={i}>{message}</li>;
         })}
       </ul>
     </div>
   );
 }
Example #13
0
 invoke(mod, phase, store) {
   // TODO: recursively visit imports
   let body = mod.body.filter(_.complement(isCompiletimeStatement)).map(term => {
     term = term.gen(); // TODO: can we remove the need for gen? have to deeply remove compiletime code
     if (isVariableDeclarationStatement(term)) {
       this.registerVariableDeclaration(term.declaration, phase, store);
     } else if (isFunctionDeclaration(term)) {
       this.registerFunctionOrClass(term, phase, store);
     }
     return term;
   });
   let exportsObj = evalRuntimeValues(body, _.merge(this.context, {
     store, phase
   }));
   return store;
 }
async function getViewsText(pid) {
  const selector = '#pl-header .pl-header-details li';
  const options = {
    uri: 'https://www.youtube.com/playlist',
    headers: { 'accept-language': 'en' },
    qs: { list: pid },
    transform: (body) => cheerio.load(body)
  };

  const findViewsText = R.find(R.pipe(R.match(/view/), R.complement(R.isEmpty)));

  const $ = await request(options);
  const selText = $(selector).map((key, val) => $(val).text()).get();

  if (R.isEmpty(selText)) {
    throw new Error('playlist is not suitable');
  }

  return findViewsText(selText);
}
Example #15
0
export const createModule = (reference, { schema, methods, component }) => {

    const [name, inherits] = (() => {
        const regExp = /^(.+?)(?:\/(.+?))?$/i;
        const matches = reference.match(regExp);
        return [matches[2] || matches[1], matches[2] ? matches[1] : undefined];
    })();

    try {

        return document.registerElement(name, pickBy(complement(isNil), {
            prototype: getPrototype({ inherits, schema, methods, component }),
            extends: inherits
        }));

    } catch (e) {
        return void throwError(e.message);
    }

};
    .then(function linterSuccess (lint) {
      var results = lint.results;

      if (options.emitErrors === false) {
        warnings = results.filter(R.either(fileHasErrors, fileHasWarnings));
      } else {
        warnings = results.filter(R.both(R.complement(fileHasErrors), fileHasWarnings));
        errors = results.filter(fileHasErrors);
      }

      if (options.quiet === false) {
        console.warn(options.formatter(results));
      }

      if (options.failOnError && errors.length) {
        done(new Error(errorMessage));
      } else {
        done();
      }
    })
Example #17
0
// Given a patch as a raw string, get them back as a more useful grouped list of
// lines [
//  {header, hunk}
// ]
function groupPatches (patchStr) {
  const lines = R.split('\n', patchStr)

  // Helper function to build our list of patches
  const headers = []
  const hunks = []
  const isHeader = R.test(/^@@.*@@$/)
  const isHunk = R.complement(isHeader)
  // Create a recursive function with side effects and then immediately invoke
  // it. Not the best way to do things, but I can't figure out the 'functional'
  // way
  const group = (patches) => {
    if (R.isEmpty(patches)) return

    const headerLine = R.head(patches)
    const hunkLines = R.pipe(
      R.tail,
      R.takeWhile(isHunk)
    )(patches)
    headers.push(headerLine)
    hunks.push(hunkLines)

    // Determine what the rest of the patches are
    let remainder = R.tail(patches)
    remainder = R.dropWhile(isHunk, remainder)
    // Recursive call
    group(remainder)
  }

  group(lines)
  // Headers and hunks will now be filled up

  const zipper = (header, hunk) => {
    return { header, hunk }
  }

  // Now we can finally return the data in a useful format
  return R.zipWith(zipper, headers, hunks)
}
Example #18
0
export const splitEveryTime = curry((predicate, list) => {
  const splitIndexes = pipe(
    reduceIndexed((acc, item, index) => {
      if (predicate(item)) {
        return [...acc, index]
      }

      return acc
    }, []),
    insert(list.length - 1, list.length)
  )(list)

  const split = mapIndexed((splitIndex, i, splitIndexList) => {
    const previousIndex = defaultTo(0, splitIndexList[i - 1])
    const currentIndex = splitIndexList[i]

    return slice(previousIndex, currentIndex, list)
  })

  return pipe(
    split,
    filter(complement(isEmpty))
  )(splitIndexes)
})
const gte = _.anyPass([_.gt, _.equals]);
const ge: boolean = gte(3, 2);

//$ExpectError
const gt10 = x => x > 10;
//$ExpectError
const even = x => x % 2 === 0;
const f = _.both(gt10, even);

const b: boolean = f("");
const b_: boolean = f(100);

//$ExpectError
const isEven = n => n % 2 === 0;
const isOdd = _.complement(isEven);

const c: boolean = isOdd("");
const c_: boolean = isOdd(2);

const fn = _.cond([
  [_.equals(0), _.always("water freezes at 0°C")],
  [_.equals(100), _.always(1)],
  [_.T, temp => "nothing special happens at " + temp + "°C"]
]);
const cond_: number | string = fn(0);

// This is abit awkward — if a non-null value of type
// differrent to number is passed flow will infer a union type
// for all of them
const defaultTo42 = _.defaultTo(42);
//$ExpectError
const topE: Array<["a" | "b" | "c" | "z", number]> = _.toPairs({
  a: 1,
  b: 2,
  c: 3
});

const F = function() {
  this.x = "X";
};
F.prototype.y = "Y";
const f = new F();
const topin = _.toPairsIn(f);

const val = _.values({ a: 1, b: 2, c: true });
const val1: number | boolean = val[0];

const pred = _.where({
  a: (a: string) => a === "foo",
  b: _.complement(_.equals("bar")),
  c: (c: Object) => !!c,
  x: _.gt(10),
  y: _.lt(20)
});

const w: boolean = pred({ a: "foo", b: "xxx", x: 11, y: 19 });

const pred1 = _.whereEq({ a: 1, b: 2 });

const win: boolean = pred1({ a: 1, d: 1 });
Example #21
0
	defaultsR: (def, obj) => Ru.mergeR(def, Ru.filterObjR(R.complement(is.undefined) ,obj)),
Example #22
0
	defaults: (def, obj) => R.merge(def, Ru.filterObj(R.complement(is.undefined) ,obj)),
Example #23
0
var step = function(scenarios) {
    var thenClauses = toBeApplied(scenarios);

    return R.map(R.unless(R.complement(R.prop('unapplied')),applyThenClauses(thenClauses)),
                 markUnaplied(scenarios));
}
Example #24
0
export const average = (...items) => {
    items = items.filter(complement(equals(undefined)))

    return sum(items) / items.length
}
Example #25
0
import R from 'ramda';
import mapSpecimenOption from './mapSpecimenOption';

const removeEmpty = R.filter(R.complement(R.isEmpty));
const splitType = R.compose(removeEmpty, R.split('|'));
const splitOptions = R.compose(removeEmpty, R.split(','));

const camelize = (str) => str.replace(/-(\w)/g, (_, c) => c.toUpperCase());

const nothing = () => null;
const mapSpanToProp = mapSpecimenOption(/^span-(\d)$/, (v) => ({span: +v}));
const camelizeOption = (option) => ({[camelize(option)]: true});

const optionToKeyValue = (mapOptionsToProps) => (option) => {
  for (let mapper of [mapOptionsToProps, mapSpanToProp]) {
    if (typeof mapper === 'function') {
      const prop = mapper(option);
      if (prop !== null) {
        return prop;
      }
    }
  }
  return camelizeOption(option);
};

const parseSpecimenOptions = (mapOptionsToProps = nothing) => (options = '') => {
  const [, restOptions = ''] = splitType(options);
  return R.mergeAll(splitOptions(restOptions).map(optionToKeyValue(mapOptionsToProps)));
};

export default parseSpecimenOptions;
Example #26
0
  typeof window !== 'undefined'
    && window.document
    && window.document.createElement
)

export const isReactNative = () => (
  typeof window !== 'undefined'
    && window.navigator
    && window.navigator.product === 'ReactNative'
)

export const getTimeFunc = () => (
  (Date.now)
    ? () => Date.now()
    : () => new Date().getTime()
)

export default {

  now: getTimeFunc(),

  isOnServer: R.once(
    R.complement(
      R.anyPass([
        canUseDOM,
        isReactNative
      ])
    )
  )
}
Example #27
0
import R from 'ramda'

/**
 * Checks if something is not null or undefined.
 *
 * @since v1.0.0
 * @param {*} (*) The thing to check.
 * @return {Boolean} True if it is not nil; false otherwise.
 * @example
 * RS.isNotNil(null) //=> false
 */
const isNotNil = R.complement(R.isNil)

export default isNotNil
Example #28
0
import { complement } from 'ramda'
import isWithin from './isWithin'

/**
 * Given a min and max, determines if the value is not
 * included in the range.
 *
 * This function is curried.
 *
 * @since v1.0.0
 * @sig Number a -> a -> a -> a
 * @param {Number} the minimum number
 * @param {Number} the maximum number
 * @param {Number} the value to test
 * @return {Boolean} True if the value is not included; otherwise false.
 * @example
 * RS.isNotWithin(1, 5, 3) //=> false
 * RS.isNotWithin(1, 5, 1) //=> false
 * RS.isNotWithin(1, 5, 5) //=> false
 * RS.isNotWithin(1, 5, 5.1) //=> true
 */
// export default R.curry((min, max, value) => R.complement(isWithin(min, max, value)))
export default complement(isWithin)
Example #29
0
import R from 'ramda'
import RS from 'ramdasauce'

const isIoValid = (io) => !R.isNil(io)
const isHostValid = R.allPass([R.complement(RS.isNilOrEmpty), R.is(String)])
const isPortValid = R.allPass([R.complement(R.isNil), R.is(Number), RS.isWithin(1, 65535)])
const onCommandValid = (fn) => typeof fn === 'function'

/**
 * Ensures the options are sane to run this baby.  Throw if not.  These
 * are basically sanity checks.
 */
const validate = (options) => {
  const { io, host, port, onCommand } = options

  if (!isIoValid(io)) throw new Error('invalid io function')
  if (!isHostValid(host)) throw new Error('invalid host')
  if (!isPortValid(port)) throw new Error('invalid port')
  if (!onCommandValid(onCommand)) throw new Error('invalid onCommand handler')
}

export default validate
Example #30
0
  input: Object,
  requiredKeys: string[],
  messages: ErrorMessages
) => R.pick(R.difference(requiredKeys, filledOutFields(input)), messages)

export const checkProp = R.curry((key, message, predicates, profile) => {
  if (R.propSatisfies(R.allPass(R.flatten([predicates])), key, profile)) {
    return {}
  }
  return { [key]: message }
})

export const checkIsNotNilOrEmpty = checkProp(
  R.__,
  R.__,
  R.complement(isNilOrEmptyString)
)

export const mergeValidations = R.compose(
  R.converge(
    R.compose(
      R.mergeAll,
      Array.of
    )
  ),
  Array.of
)

export const checkMaxLength = R.curry((key, label, maxLength, profile) =>
  checkProp(
    key,