Skip to content

Instantly share code, notes, and snippets.

@Siilwyn
Forked from evilsoft/bigTest.txt
Last active June 7, 2018 21:59
Show Gist options
  • Save Siilwyn/f4951733b089869a4e72bad535e667dc to your computer and use it in GitHub Desktop.
Save Siilwyn/f4951733b089869a4e72bad535e667dc to your computer and use it in GitHub Desktop.
Fun for Selwyn
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')
)
const {
Async, constant, curry,
mapReduce, maybeToAsync,
safe
} = require('crocks')
// access :: (String, Number) -> Async Error ()
const access =
Async.fromNode(fs.access)
// readFile :: (String, String) -> Async Error a
const readFile =
Async.fromNode(fs.readFile)
const accessAsync = curry(
(mode, path) =>
access(path, mode)
.map(constant(path))
)
// readFileAsync :: Options -> a -> Async Error b
const readFileAsync = curry(
(options, path) =>
readFile(path, options)
)
const checkRead =
accessAsync(fs.constants.F_OK)
const readtextFile =
readFileAsync('utf-8')
const loadTextFile =
composeK(readTextFile, checkRead)
const fork =
a => a.fork(
console.log.bind(null, 'rej'),
console.log.bind(null, 'res')
)
module.exports = {
loadTextFile,
fork,
}
const { Async, mapReduce } = require('crocks');
const { loadTextFile, fork } = require('./funcs.js');
const data = [
'./missing.txt',
'./test.txt',
'./bigTest.txt'
]
const concat = (acc, x) =>
acc.alt(x)
const flow = mapReduce(
loadTextFile,
concat,
Async.rejected(new Error('list is empty'))
)
fork(flow(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment