Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new exercise grep #752

Merged
merged 7 commits into from
Jan 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1430,6 +1430,18 @@
"strings"
],
"deprecated": true
},
{
"slug": "grep",
"uuid": "78bcbae1-a0f2-460c-ba89-e51844fe9397",
"core": false,
"unlocked_by": "matrix",
"difficulty": 4,
"topics": [
TomPradat marked this conversation as resolved.
Show resolved Hide resolved
"files",
"searching",
"text_formatting"
]
}
]
}
26 changes: 26 additions & 0 deletions exercises/grep/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"root": true,
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 7,
"sourceType": "module"
},
"env": {
"es6": true,
"node": true,
"jest": true
},
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"rules": {
"linebreak-style": "off",

"import/extensions": "off",
"import/no-default-export": "off",
"import/no-unresolved": "off",
"import/prefer-default-export": "off"
}
}
102 changes: 102 additions & 0 deletions exercises/grep/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Grep

Search a file for lines matching a regular expression pattern. Return the line
number and contents of each matching line.

The Unix [`grep`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html) command can be used to search for lines in one or more files
that match a user-provided search query (known as the *pattern*).

The `grep` command takes three arguments:

1. The pattern used to match lines in a file.
2. Zero or more flags to customize the matching behavior.
3. One or more files in which to search for matching lines.

Your task is to implement the `grep` function, which should read the contents
of the specified files, find the lines that match the specified pattern
and then output those lines as a single string. Note that the lines should
be output in the order in which they were found, with the first matching line
in the first file being output first.

As an example, suppose there is a file named "input.txt" with the following contents:

```text
hello
world
hello again
```

If we were to call `grep "hello" input.txt`, the returned string should be:

```text
hello
hello again
```

### Flags

As said earlier, the `grep` command should also support the following flags:

- `-n` Print the line numbers of each matching line.
- `-l` Print only the names of files that contain at least one matching line.
- `-i` Match line using a case-insensitive comparison.
- `-v` Invert the program -- collect all lines that fail to match the pattern.
- `-x` Only match entire lines, instead of lines that contain a match.

If we run `grep -n "hello" input.txt`, the `-n` flag will require the matching
lines to be prefixed with its line number:

```text
1:hello
3:hello again
```

And if we run `grep -i "HELLO" input.txt`, we'll do a case-insensitive match,
and the output will be:

```text
hello
hello again
```

The `grep` command should support multiple flags at once.

For example, running `grep -l -v "hello" file1.txt file2.txt` should
print the names of files that do not contain the string "hello".

## Setup

Go through the setup instructions for Javascript to install the necessary
dependencies:

[https://exercism.io/tracks/javascript/installation](https://exercism.io/tracks/javascript/installation)

## Requirements

Install assignment dependencies:

```bash
$ npm install
```

## Making the test suite pass

Execute the tests with:

```bash
$ npm test
```

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing `xtest` to
`test`.

## Source

Conversation with Nate Foster. [http://www.cs.cornell.edu/Courses/cs3110/2014sp/hw/0/ps0.pdf](http://www.cs.cornell.edu/Courses/cs3110/2014sp/hw/0/ps0.pdf)

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have
completed the exercise.
14 changes: 14 additions & 0 deletions exercises/grep/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
presets: [
[
'@babel/env',
{
targets: {
node: 'current',
},
useBuiltIns: false,
},

],
],
};
9 changes: 9 additions & 0 deletions exercises/grep/data/iliad.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Achilles sing, O Goddess! Peleus' son;
His wrath pernicious, who ten thousand woes
Caused to Achaia's host, sent many a soul
Illustrious into Ades premature,
And Heroes gave (so stood the will of Jove)
To dogs and to all ravening fowls a prey,
When fierce dispute had separated once
The noble Chief Achilles from the son
Of Atreus, Agamemnon, King of men.
7 changes: 7 additions & 0 deletions exercises/grep/data/midsummer-night.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
I do entreat your grace to pardon me.
I know not by what power I am made bold,
Nor how it may concern my modesty,
In such a presence here to plead my thoughts;
But I beseech your grace that I may know
The worst that may befall me in this case,
If I refuse to wed Demetrius.
8 changes: 8 additions & 0 deletions exercises/grep/data/paradise-lost.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Of Mans First Disobedience, and the Fruit
Of that Forbidden Tree, whose mortal tast
Brought Death into the World, and all our woe,
With loss of Eden, till one greater Man
Restore us, and regain the blissful Seat,
Sing Heav'nly Muse, that on the secret top
Of Oreb, or of Sinai, didst inspire
That Shepherd, who first taught the chosen Seed
95 changes: 95 additions & 0 deletions exercises/grep/example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#!/usr/bin/env node
const fs = require("fs");

// Helpers
const availables_options = [
"n", // add line numbers
"l", // print file names where pattern is found
"i", // ignore case
"v", // reverse files results
"x" // match entire line
];

const does_line_matche_pattern = (line, pattern) => {
let left = line;
let right = pattern;

if (is_option_set("i")) {
left = line.toLowerCase();
right = pattern.toLowerCase();
}

if (is_option_set("x")) {
return left === right;
}

return left.match(right) !== null;
};

const getConfigFromArgs = () => {
const config = {
pattern: "",
options: [],
files: []
};

let has_pattern_been_found = false;

process.argv.slice(2).forEach(val => {
if (has_pattern_been_found) {
config.files.push(val);
} else if (val.indexOf("-") !== -1) {
const option = val.replace("-", "");

if (!availables_options.includes(option)) {
throw new Error(`Unknown option ${option}`);
}

config.options.push(option);
} else {
has_pattern_been_found = true;
config.pattern = val;
}
});

return config;
};

const config = getConfigFromArgs();
const is_option_set = option => config.options.includes(option);

// Actual script
config.files.forEach(file => {
const data = fs.readFileSync(file, { encoding: "utf-8" });

if (is_option_set("l")) {
data.split("\n").find(line => {
const does_line_match_pattern = does_line_matche_pattern(line, config.pattern);

return is_option_set("v") ? !does_line_match_pattern : does_line_match_pattern;
}) && console.log(file);
} else {
data.split("\n").forEach((line, index) => {
let result = "";
let should_output_line = does_line_matche_pattern(line, config.pattern);

if (is_option_set("v")) {
should_output_line = !should_output_line;
}

if (should_output_line) {
if (config.files.length > 1) {
result += `${file}:`;
}

if (is_option_set("n")) {
result += `${index + 1}:`;
}

result += line;

console.log(result);
}
});
}
});
15 changes: 15 additions & 0 deletions exercises/grep/grep.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node

// The above line is a shebang. On Unix-like operating systems, or environments, this will allow the script to be
// run by node, and thus turn this JavaScript file into an executable. If you don't have a Unix-like operating
// system or environment, for example Windows without WSL, you can use
//
TomPradat marked this conversation as resolved.
Show resolved Hide resolved
// node grep.js args
//
// Instead of "./grep.js args".
//
// Read more about shebangs here: https://en.wikipedia.org/wiki/Shebang_(Unix)
//
// This is only a SKELETON file for the 'Grep' exercise. It's been provided as a
// convenience to get you started writing code faster.
//
Loading