From 87759ccee94c3d16f770ac945fac115521b3e6e5 Mon Sep 17 00:00:00 2001 From: Douglas Matoso Date: Mon, 26 Mar 2018 21:58:29 -0300 Subject: [PATCH] Fix #13: Add option -r to select a random cow (#30) * Fix #13: Add option -r to select a random cow * Fix indentation --- cli.js | 9 +++++---- index.js | 11 ++++++++++- lib/cows.js | 19 +++++++++++++------ 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/cli.js b/cli.js index 3f55ca2..e573138 100755 --- a/cli.js +++ b/cli.js @@ -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) { @@ -64,9 +65,9 @@ function say () { function listCows () { require("./index").list(function(err, list) { - if (err) throw new Error(err); - console.log(list.join(" ")); - }); + if (err) throw new Error(err); + console.log(list.join(" ")); + }); } function showHelp () { diff --git a/index.js b/index.js index 54254e6..35b5edf 100644 --- a/index.js +++ b/index.js @@ -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"; diff --git a/lib/cows.js b/lib/cows.js index e31f1be..8ebf14d 100644 --- a/lib/cows.js +++ b/lib/cows.js @@ -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]; @@ -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)) +}