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

Fix #13: Add option -r to select a random cow #30

Merged
merged 3 commits into from
Mar 27, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ var argv = require("optimist")
"n" : "If it is specified, the given message will not be word-wrapped.",
"W" : "Specifies roughly where the message should be wrapped. The default is equivalent to -W 40 i.e. wrap words at or before the 40th column.",
"f" : "Specifies a cow picture file (''cowfile'') to use. It can be either a path to a cow file or the name of one of cows included in the package.",
"r" : "Select a random cow",
"l" : "List all cowfiles included in this package."
})
.boolean(["b", "d", "g", "p", "s", "t", "w", "y", "n", "h", "l"])
.boolean(["b", "d", "g", "p", "s", "t", "w", "y", "n", "h", "r", "l"])
.argv;

if (argv.l) {
Expand Down
11 changes: 10 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,16 @@ exports.think = function (options) {
exports.list = cows.list;

function doIt (options, sayAloud) {
var cow = cows.get(options.f || "default");
var cowFile;

if (options.r) {
var cowsList = cows.listSync();
cowFile = cowsList[Math.floor(Math.random() * cowsList.length)];
} else {
cowFile = options.f || "default";
}

var cow = cows.get(cowFile);
var face = faces(options);
face.thoughts = sayAloud ? "\\" : "o";

Expand Down
19 changes: 13 additions & 6 deletions lib/cows.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ var fs = require("fs");
var replacer = require("./replacer");

var textCache = {};
var cowsPath = path.join(__dirname, "../cows");

function cowNamesFromFiles (files) {
return files.map(function (cow) {
return path.basename(cow, ".cow");
});
}

exports.get = function (cow) {
var text = textCache[cow];
Expand All @@ -25,13 +32,13 @@ exports.get = function (cow) {
}

exports.list = function (callback) {
fs.readdir(path.join(__dirname, "../cows"), function (err, files) {
fs.readdir(cowsPath, function (err, files) {
if (err) return callback(err);

var cows = files.map(function (cow) {
return path.basename(cow, ".cow");
});

return callback(null, cows);
return callback(null, cowNamesFromFiles(files));
});
}

exports.listSync = function () {
return cowNamesFromFiles(fs.readdirSync(cowsPath))
}