Options
All
  • Public
  • Public/Protected
  • All
Menu

Lodash-Fun

Some fun utilities, logic functions and stuff that is not included with lodash/fp.

Designed to be used hand in hand with Lodash/fp

Written in TypeScript but usage in JS is perfectly fine. Named this way because I couldn't believe it wasn't taken.

Including

  • Composable logic functions - andWith, orWith, ifElseWith, switchWith
  • hasKeysWith - inspecting object values
  • Object flattening/unflattening
  • deepConform - a powerful async object validation function.

Full TypeDoc documentation can be found here!

Index

Type aliases

TypeOrErr

TypeOrErr<T>: T | Error

Type parameters

  • T

Variables

Const conform

conform: CurriedFunction2<any, any, any> = curry((validatorObj, config) => {return transformKeys(validatorObj, config).then((result) => {return conformTransformed(result)})})

Const curriedAndWith

curriedAndWith: CurriedFunction3<any, any, any, any> = curry((fA,fB, a) => (fA(a) && fB(a)) )

Const curriedHasKeysWith

curriedHasKeysWith: CurriedFunction3<any, any, any, boolean> = curry((k, cfun, o)=>{return every((item) => {return has(item, o) ? cfun(get(item, o)) : false}, k)})

Const curriedIfElseWith

curriedIfElseWith: CurriedFunction4<any, any, any, any, any> = curry((c, tCond, fCond, arg) => c(arg) ? tCond(arg) : fCond(arg))

Const curriedMissingKeysDeep

curriedMissingKeysDeep: CurriedFunction2<any, any, string[]> = curry((compareObj: any, srcObj: any): string[] =>{let flatCompare = keys(flattenKeys(compareObj))let flatSrc = keys(flattenKeys(srcObj))return reduce((acc, item) => {return without([item], acc) //?}, flatCompare, flatSrc)})

Const curriedOrWith

curriedOrWith: CurriedFunction3<any, any, any, any> = curry((fA,fB, a) => (fA(a) || fB(a)))

Const curriedSwitchWith

curriedSwitchWith: CurriedFunction3<any, any, any, any> = curry((cC, sO, a) => sO[cC(a)](a) )

Const defaultFormat

defaultFormat: (a1: A1) => R3 = compose(join('\n'),map(([k,v]) => {return `${k}: ${v.message}`}), toPairs)

Type declaration

    • (a1: A1): R3
    • Parameters

      • a1: A1

      Returns R3

Const errorsFrom

errorsFrom: any = compose(omitBy(negate(isError)),flattenKeys)

Const transform

transform: CurriedFunction2<any, any, any> = curry((validatorObj, config): Bluebird<any> =>{const recurTransform = (v, c) => {return Bluebird.try(() => {let confObj = !!c ? c : {}let transformed = uncappedMapValues((val, idx) => {if(isFunction(val)) {return Bluebird.try(() => val(get(idx, confObj), config)).catch(identity)}if(isObject(val)) {return Bluebird.props(recurTransform(val, confObj[idx]))// .catch(err => {// // console.log(err)// return err.validationErrors// })}return Promise.resolve(val)}, v)return Bluebird.props(transformed)})}return recurTransform(validatorObj, config)})

Const uncappedMapValues

uncappedMapValues: any = mapValues.convert({cap: false})

Const unflatten

unflatten: (a1: A1) => R2 = compose(reduce((acc, [k, v]) => set(k, v, acc), {}), toPairs)

Type declaration

    • (a1: A1): R2
    • Parameters

      • a1: A1

      Returns R2

Functions

andWith

  • Applies its third argument to Functions FunA and FunB returning the logical AND of their results.

    let A (arg) => arg >= 5
    let B (arg) => arg <= 10
    let betweenFiveAndTen = andWith(A, B)
    betweenFiveAndTen(6) //true
    betweenFiveAndTen(11) //false

    Parameters

    • funA: ReturnsType<boolean>

      The first function to apply arg to.

    • Optional funB: ReturnsType<boolean>

      The second function to apply arg to.

    • Optional arg: any

      The value to apply to funA and funB

    Returns any

    The logical AND of the result of funA(arg), funB(arg) - (funA(arg) && funB(arg))

composeP

  • composeP<T>(...funs: ((val: any) => any)[]): (initial: T) => Promise<any>
  • Creates a function that resolves the result of applying the given functions from right to left.

    let FromRightToLeft = composeP(
       s => `${s} Left`,
       s => `${s} to` ,
       s => `${s} Right`
       )
    
    await FromRightToLeft('From') // From Right to Left
    

    Type parameters

    • T

    Parameters

    • Rest ...funs: ((val: any) => any)[]

    Returns (initial: T) => Promise<any>

    function

      • (initial: T): Promise<any>
      • Parameters

        • initial: T

        Returns Promise<any>

conformDeep

  • Accepts an object containing functions to be applied to each property value in the second argument.

    see

    ConformDeepValidator For details on the full validator object.

    see

    ConformDeepValidatorFun For details on the arguments and return values of validator functions.

    see

    [[ConformDeepError]] For details on the rejection value from a failing conformDeep


    Returns a Promise containing the validated object unless any of the individual validators throw or return an Error object. Rejects with [[ConformDeepError]] otherwise, containing a flattenKeys representation of the errors encountered.

    const personValidator: ConformDeepValidator = {
      name: (name, srcObj): TypeOrErr<string> => !!name ? name : 'No Name!',
      age: (age, srcObj): TypeOrErr<Promise<string>| string> => !!age ? age : Promise.resolve(0), // Can be Async
    }
    
    const validatePerson = conformDeep(personValidator)
    validatePerson({}) // {name: 'No name', age: 0}
    validatePerson({name: 'bob, age: 47}) // {name: 'Bob', age: '47'}

    Parameters

    • validatorObj: ConformDeepValidator | object

      An object containing functions matching your expected srcObj

    • Optional srcObj: object

    Returns any

    Curried function accepting srcObj or a Promise containing the conforming object.

Const conformTransformed

  • conformTransformed(o: any): any
  • Parameters

    • o: any

    Returns any

Const flatten

  • flatten(obj: object, path?: string[]): {}

flattenKeys

  • flattenKeys(obj: object): {}
  • Flattens objects into an un-nested object with property names computed from its nested paths.

    let obj = {
      a: {
        b: 'Im nested'
      },
      c: [1,2,3,4]
    }
    
    flattenKeys(obj)
    // {"a.b": 'I'm nested', "c.0": 1, "c.1": 2, "c.2": 3, "c.3": 4}

    Parameters

    • obj: object

      The object to flatten.

    Returns {}

    • [key: string]: any

flowP

  • flowP<T>(...funs: ((val: any) => any)[]): (initial: T) => Promise<any>
  • Creates a function that resolves the result of applying the given functions from left to right.

    let FromRightToLeft = flowP(
       s => `${s} Left`,
       s => `${s} to` ,
       s => `${s} Right`
       )
    
    await FromLeftToRight('From') // From Left to Right
    

    Type parameters

    • T

    Parameters

    • Rest ...funs: ((val: any) => any)[]

    Returns (initial: T) => Promise<any>

    function

      • (initial: T): Promise<any>
      • Parameters

        • initial: T

        Returns Promise<any>

formatConformError

  • formatConformError(conformError: ConformError, formatter?: (a1: A1) => R3): string
  • Accepts a ConformError instance and formats its validationErrors into human readable form.

    Parameters

    • conformError: ConformError
    • Default value formatter: (a1: A1) => R3 = defaultFormat
        • (a1: A1): R3
        • Parameters

          • a1: A1

          Returns R3

    Returns string

hasKeysWith

  • hasKeysWith(keys: string[], constraintFun?: (item: any) => boolean, obj?: any): (CurriedFunction3<any, any, any, boolean> & CurriedFunction2<any, any, boolean> & CurriedFunction1<any, boolean> & false) | (CurriedFunction3<any, any, any, boolean> & CurriedFunction2<any, any, boolean> & CurriedFunction1<any, boolean> & true)
  • Ensures its third argument contains the keys in keys and that each passes constraintFun

    let keys = ['a', 'b', 'c']
    let constraint = v => v > 10
    let allGt10 = hasKeysWith(keys, constraint)
    allGt10({a: 11, b: 20, c: 30}) //true
    allGt10({b: 20, c: 30}) //false
    allGt10({a: 9, b: 20, c: 30}) //false

    Parameters

    • keys: string[]

      Array of keys expected in obj

    • Optional constraintFun: (item: any) => boolean

      applied to every key if found in obj

        • (item: any): boolean
        • Parameters

          • item: any

          Returns boolean

    • Optional obj: any

    Returns (CurriedFunction3<any, any, any, boolean> & CurriedFunction2<any, any, boolean> & CurriedFunction1<any, boolean> & false) | (CurriedFunction3<any, any, any, boolean> & CurriedFunction2<any, any, boolean> & CurriedFunction1<any, boolean> & true)

ifElseWith

  • Applies its fourth argument to the first argument comparator returning the result of passing arg to trueConditionFun if true or to falseConditionFun if false.

    let comparator = (arg) => arg >= 100
    let tCond = (arg) => `${arg} is less than 100...`
    let fCond = (arg) => `${arg} is large enough to work`
    let testNumber = ifElseWith(comparator, tCond, fCond)
    testNumber(99) // '99 is less than 100...'
    testNumber(101) // '101 is large enough to work.
    ls100gt200(150) //false

    Parameters

    • comparator: ReturnsType<boolean>

      Evaluated with arg

    • Optional trueConditionFun: ReturnsType<any>

      Called with arg and returned if comparator(arg) is true.

    • Optional falseConditionFun: ReturnsType<any>

      Called with arg and returned if comparator(arg) is false

    • Optional arg: any

    Returns any

    The result of trueConditionFun(arg) if comparator(arg) is true, falseConditionFun(arg) otherwise. return comparator(arg) ? trueConditionFun(arg) : falseConditionFun(arg)

isConformError

  • Checks for Type ConformDeepError

    Parameters

    Returns error is ConformError

Const isValid

  • isValid(flattenedErrs: any): boolean
  • Parameters

    • flattenedErrs: any

    Returns boolean

missingKeysDeep

  • missingKeysDeep(srcObj: any, testObject?: any): CurriedFunction2<any, any, string[]> & CurriedFunction1<any, string[]> & string[]
  • Deeply compares testObj keys with srcObj keys, returning an array of missing paths.

    missingKeysDeep({a: 1, b: {c: 2, d: 3}}, {a: 1, b: {c: 2, d: 3}}) // []
    missingKeysDeep({a: 1, b: {c: 2}}, {a: 1}) // ['b.c', 'b.d']

    Parameters

    • srcObj: any
    • Optional testObject: any

    Returns CurriedFunction2<any, any, string[]> & CurriedFunction1<any, string[]> & string[]

orWith

  • Applies its third argument to Functions FunA and FunB returning the logical OR of their results.

    let A (arg) => arg < 100
    let B (arg) => arg > 200
    let ls100gt200 = andWith(A, B)
    ls100gt200(99) //true
    ls100gt200(201) //true
    ls100gt200(150) //false

    Parameters

    • funA: ReturnsType<boolean>

      The first function to apply arg to.

    • Optional funB: ReturnsType<boolean>

      The second function to apply arg to.

    • Optional arg: any

      The value to apply to funA and funB

    Returns any

    The logical OR of the result of funA(arg), funB(arg) - (funA(arg) || funB(arg))

switchWith

  • switchWith(computeCase: (arg: any) => string, switchObj?: any, arg?: any): any
  • Chooses a path of execution by calling the function in switchObj whose key is determined by passing its third argument to computeCase.

    let computeCase = item => !(item % 2) ? 'even' : 'odd'
    let switchObj = {
      even: i => `${i} is even`,
      odd: i => `${i} is odd.`
    }
    
    let randomResult = switchWith(computeCase, switchObj)
    randomResult(6) // '6 is even'
    randomResult(301) // '301 is odd'
    

    Parameters

    • computeCase: (arg: any) => string

      Determines the key of switchObj

        • (arg: any): string
        • Parameters

          • arg: any

          Returns string

    • Optional switchObj: any

      Object literal containing Functions which will be called with arg.

    • Optional arg: any

    Returns any

    the result of the expression: switchObj[computeCase(arg)](arg)

transformKeys

  • transformKeys(transformObj: KeyTransformer | object, srcObj?: object): any
  • Accepts an object containing functions to be applied to each property value in the second argument.

    see

    ConformDeepValidator For details on the full validator object.

    see

    ConformDeepValidatorFun For details on the arguments and return values of validator functions.

    see

    [[ConformDeepError]] For details on the rejection value from a failing conformDeep


    Returns a Promise containing the validated object unless any of the individual validators throw or return an Error object. Rejects with [[ConformDeepError]] otherwise, containing a flattenKeys representation of the errors encountered.

    const personValidator: ConformDeepValidator = {
      name: (name, srcObj): TypeOrErr<string> => !!name ? name : 'No Name!',
      age: (age, srcObj): TypeOrErr<Promise<string>| string> => !!age ? age : Promise.resolve(0), // Can be Async
    }
    
    const validatePerson = conformDeep(personValidator)
    validatePerson({}) // {name: 'No name', age: 0}
    validatePerson({name: 'bob, age: 47}) // {name: 'Bob', age: '47'}

    Parameters

    • transformObj: KeyTransformer | object

      An object containing functions matching your expected srcObj

    • Optional srcObj: object

    Returns any

    Curried function accepting srcObj or a Promise containing the conforming object.

unflattenKeys

  • unflattenKeys(obj: object): object
  • Unflattens objects.

    let flat = {
      'a.b': 'Ok',
      'c.d': 'Also ok'
    }
    
    unflattenKeys(flat)
    //{a: {b: 'Ok'}, c: {d: 'Also ok}}

    Parameters

    • obj: object

      The flattened object you wish to unflatten.

    Returns object

Legend

  • Constructor
  • Property
  • Inherited property
  • Static property

Generated using TypeDoc