diff --git a/lib/index.js b/lib/index.js index 95c1236..a36bec0 100644 --- a/lib/index.js +++ b/lib/index.js @@ -15,9 +15,22 @@ function random () { return quotes[Math.floor(Math.random() * quotes.length)]; } +/** + * `random_by_tag` returns a random quote for a specific tag + * returns Object - a random quote from the list with the desired tag + */ +function random_by_tag (tag) { + const q_by_tag = quotes.filter((q) => { + return q.text.includes(tag) || (q.tags && q.tags.includes(tag)) + }) + return q_by_tag[Math.floor(Math.random() * q_by_tag.length)]; +} + + module.exports = { parse_json: parse_json, - random: random + random: random, + random_by_tag: random_by_tag }; diff --git a/test/index.test.js b/test/index.test.js index 0a45c7f..8990913 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -36,3 +36,12 @@ test('quotes.random returns a random quote object', function (t) { t.ok(Object.keys(random_quotes_list).length < 200); t.end(); }); + +test('quotes.random_by_tag returns a random quote object by tag', function (t) { + const tag = "time"; + const q = quotes.random_by_tag(tag); + // check that the quote returned contains the tag in either text or tags: + const truthy = q.text.includes(tag) || q.tags && q.tags.includes(tag); + t.ok(truthy); + t.end(); +});