/ JavaScript

Better `read` and `write`

The first version of the functional asynchronous read and write[1] require simple values to be wrapped into the callback function.

var value = value => result => result(null, value);
save(value('test1.out'), value('ok'))();

Of course, the implementation of the read and write can help developer a bit and accept both simple and callback values:

var read = filepath =>  
  callback => {
    let impl = filepath => {
      let options = { encoding : 'utf8' };
      fs.readFile(filepath, options, callback);
    return ('function' === typeof filepath)
      ? filepath((_, filepath) => impl(filepath))
      : impl(filepath);

var write = (filepath, data) =>
  callback => {
    let impl1 = (filepath, data) =>
      fs.writeFile(filepath, data, callback);
    let impl2 = filepath =>
      ('function' === typeof data)
        ? data((_, data) => impl1(filepath, data))
        : impl1(filepath, data);
    return ('function' === typeof filepath)
      ? filepath((_, filepath) => impl2(filepath))
      : impl2(filepath);

Now it is possible to mix simple and asynchronous values in arguments:

// creates test1.out file with "ok" in it
save('test1.out', 'ok')();

// copies test.in into test.out
write('test.out', read('test.in'))();

// prints content of the test.in file
read('test.in')((_, data) => console.log(data));

  1. Functional Asynchronous Programming in node.js, https://alexatnet.com/functional-asynchronous-programming-in-node-js/ ↩︎

Alex Netkachov

Alex Netkachov

Alex likes functional programming and algorithms. Apart from programming, his favourites are walking with his family in the parks and national trails and reading about universe and history.

Read More