Skip to content

Commit

Permalink
add quotes.random_by_tag function in JavaScript Land #4
Browse files Browse the repository at this point in the history
  • Loading branch information
nelsonic committed Oct 17, 2019
1 parent 0d1b180 commit d78b7c2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
};
9 changes: 9 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

0 comments on commit d78b7c2

Please sign in to comment.