Trying to figure out how the IO monad works.
Using the code below I read filenames.txt
and use the results to rename files in the directory testfiles
. This is obviously unfinished, so instead of actually renaming anything I log to console. :)
My questions are:
- I call
runIO
twice, but it feels like it only should be called once, in the end? - I'm want to use
renameIO
instead ofrenaneDirect
but can't find the proper syntax.
Any other suggestions are also appreciated, I'm new to FP!
var R = require('ramda');
var IO = require('ramda-fantasy').IO
var fs = require('fs');
const safeReadDirSync = dir => IO(() => fs.readdirSync(dir));
const safeReadFileSync = file => IO(() => fs.readFileSync(file, 'utf-8'));
const renameIO = (file, name) => IO(() => console.log('Renaming file ' + file + ' to ' + name + '\n'));
const renameDirect = (file, name) => console.log('Renaming file ' + file + ' to ' + name + '\n');
safeReadFileSync("filenames.txt") // read future file names from text file
.map(R.split('\n')) // split into array
.map(R.zip(safeReadDirSync('./testfiles/').runIO())) // zip with current file names from dir
.map(R.map(R.apply(renameDirect))) // rename
.runIO(); // go!