Skip to content

Idea: add a .forEach method to each ShellString #396

@nfischer

Description

@nfischer

This would be good to add, allowing users to iterate over the stdout from a command.

This can be done in Bash by running:

for k in $(cat package.json); do # wrap each word in <> brackets and print on a new line
  echo "<$k>"
done

# Or you can change IFS (internal field separator) to break on newlines
IFS='
'
for k in $(cat package.json); do # indent each line of the output
  echo "  $k"
done

A possible API would look like:

ls().forEach(function (file) { // this already works for ls()
  echo('This is a file: ' + file);
});

// something similar could work for cat(), grep(), etc.
cat('file1.txt').forEach(function (line) {
  echo('> ' + line); // put '> ' in front of each line
});

Alternatives would be to iterate over each word (delimited by whitespace) (this is similar to bash's default behavior, which is sometimes useful).

We could also consider adding the ability to pass an option to .forEach that specifies how the output is split:

var wordCount = 0;
cat('file.txt').forEach(function (a) { wordCount++; }, {split: 'word'});
console.log(wordCount);

TODO:

  • Decide if this feature is worth adding
  • Decide if we should allow the {split: ...} option
  • Figure out a sensible default behavior when the {split: ...} option is not specified (I think "iterate over lines" and "iterate over words" are the two most sensible choices, but I'm open to other suggestions).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions