Lifts
LIghtweight Functional programming library for TypeScript
Install
yarn add lifts
npm i -S lifts
Usage
Do
Shorthand for Immediately Invoked Function Expression
const date = new Date('2020-04-17')
const result: number | null = Do(() => {
if (!isNaN(date)) {
return date.getDate()
} else {
return null
}
})
result
const result = (() => {
if (!isNaN(date)) {
return date.getDate()
} else {
return null
}
})()
Switch
Object-Style switch
const fn = (value: string) =>
Switch(value)(
{
a: () => 'String A',
b: () => 'String B',
},
() => null,
)
fn('a')
fn('b')
fn('c')
Result
const parseDate = (dateStr: string): IResult<Date, Error> => {
const date = new Date(dateStr)
if (!isNaN(date)) {
return Result.ok(date)
} else {
return Result.err(new Error('Invalid Date'))
}
}
parseDate('2020-04-17')
parseDate('foo')
Result.switch
const result = parseDate('2020-04-17')
Result.switch(result)({
ok: (value: Date) => {
return value.getDate()
},
err: (error: Error) => {
return null
},
})
const result = parseDate('foo')
Result.switch(result)({
ok: (value) => {
return value.getDate()
},
err: (error) => {
return null
},
})
Result.wrap
Wraps Error with Result.err()
if error caught, else wraps value with Result.ok()
.
const result = Result.wrap(() => {
if (condition) {
return true
} else {
throw new Error()
}
})
MapAsync
Pipe