Search code examples
javascriptnode.jsjslint

How can I rewrite this while loop in a JSLint-approved way?


Looking at the the "Streams 2 & 3 (pull) example" from: https://github.com/jprichardson/node-fs-extra#walk

var items = [] // files, directories, symlinks, etc
var fs = require('fs-extra')
fs.walk(TEST_DIR)
  .on('readable', function () {
    var item
    while ((item = this.read())) {
      items.push(item.path)
    }
  })
  .on('end', function () {
    console.dir(items) // => [ ... array of files]
  })

Latest version of JSLint complaints about the while:

Unexpected statement '=' in expression position.
                while ((item = this.read())) {
Unexpected 'this'.
                while ((item = this.read())) {

I'm trying to figure out how to write this in a JSLint-approved way. Any suggestions?

(Note: I'm aware there are other JSLint violations in this code ... I know how to fix those ...)


Solution

  • If you're really interested in writing this code like Douglas Crockford (the author of JSLint), you would use recursion instead of a while loop, since there are tail call optimizations in ES6.

    var items = [];
    var fs = require("fs-extra");
    var files = fs.walk(TEST_DIR);
    files.on("readable", function readPaths() {
        var item = files.read();
        if (item) {
            items.push(item.path);
            readPaths();
        }
    }).on("end", function () {
        console.dir(items);
    });