Skip to content

Instantly share code, notes, and snippets.

@evilsoft
Created June 2, 2018 22:29
Show Gist options
  • Save evilsoft/4f3f777164ede8323ba55d6ac664ae42 to your computer and use it in GitHub Desktop.
Save evilsoft/4f3f777164ede8323ba55d6ac664ae42 to your computer and use it in GitHub Desktop.
Fun for Selwyn
Hello. how are you?
Hello. how are you?
Hello. how are you?
Hello. how are you?
Hello. how are you?
const {
Async, constant, curry,
mapReduce, maybeToAsync,
safe
} = require('crocks')
// FileAsync :: Async Error String
// access :: (String, Number) -> Async Error ()
const access =
Async.fromNode(fs.access)
// read :: (String, String) -> Async Error a
const read =
Async.fromNode(fs.readFile)
// load :: String -> FileAsync
const load = file =>
access(file, fs.constants.R_OK)
.chain(constant(read(file, 'utf-8')))
// files :: [ String ]
const files = [
'./missing.txt',
'./test.txt',
'./bigTest.txt'
]
// first :: (a -> Boolean) -> FileAsync -> FileAsync -> FileAsync
const first = curry(
(pred, acc, x) =>
acc.alt(
x.chain(
maybeToAsync(new Error('thou shall not pass'), safe(pred))
)
)
)
// readFirst :: (String -> Boolean) -> [ String ] -> FileAsync
const readFirst = curry(
pred => mapReduce(
load,
first(pred),
Async.Rejected('nothing to read')
)
)
// isValid :: String -> Boolean
const isValid =
x => x.length > 25
readFirst(isValid, files)
.fork(
console.log.bind(console, 'rej\n'),
console.log.bind(console, 'res\n')
)
Hello. how are you?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment