-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjokes-cli.js
executable file
·127 lines (113 loc) · 2.79 KB
/
jokes-cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#! /usr/bin/env node
const jokes = require('jokes.dz')
/**
* Parse Arguments to get command and executing it
*/
let parseCommand = () => {
/** remove two first arguments filename, path **/
var arguments = process.argv.slice(2)
/** If there is no argument print help **/
if (arguments.length == 0) {
printHelp()
process.exit()
}
/** Get Command from the first argument **/
switch (arguments[0]) {
case "help":
printHelp()
break
case "all":
all()
break
case "random":
random()
break
case "count":
count()
break
case "search":
search(arguments[1])
break
case "filter-by-lang":
filterByLang(arguments[1])
break
case "filter-by-tag":
filterByTag(arguments.slice(1))
break
default:
throw new Error('Unknown Command ~ use "jokes-cli help" command')
break
}
}
/**
* Get all jokes and printing them
*/
let all = () => {
let result = jokes.all
printJson(result)
}
/**
* Get a random joke and printing it
*/
let random = () => {
let result = jokes.random()
printJson(result)
}
/**
* Get count jokes and print it
*/
let count = () => {
let result = jokes.count;
console.log('Jokes count : ' + result)
}
/**
* filter jokes by tags and printing them
* @param {RegExp} "." => all if there is no arguement
*/
let search = (regx = ".") => {
let result = jokes.search(regx)
printJson(result)
}
/**
* filter jokes by lang and printing them
* @param {String}
*/
let filterByLang = (lang = "") => {
let result = jokes.filterByLang(lang)
printJson(result)
}
/**
* filter jokes by tags and printing them
* @param {Array}
*/
let filterByTag = (tags = []) => {
if (tags.length < 1) {
// TODO : Error Msg
process.exit()
}
let result = jokes.filterByTag(tags)
printJson(result)
}
/**
* Print Help
*/
let printHelp = () => {
console.log("Jokes-cli : help")
console.log("It's your typical Algeria Jokes now residing on your own terminal")
console.log("Arguments : ")
console.log(" - all\t: get all jokes")
console.log(" - random\t: get a random joke")
console.log(" - count\t: get number of jokes")
console.log(" - search\t: find jokes by a regular expression 'jokes-cli search regex'")
console.log(" - filter-by-lang\t: filter jokes by language 'jokes-cli filter-by-lang fr'")
console.log(" - filter-by-tag\t: filter jokes by tag 'jokes-cli filter-by-tag tag1 tag2'")
// TODO: more help
}
/**
* Print pretty json
*/
let printJson = (obj) => {
console.log(JSON.stringify(obj, null, 4));
}
/** Start Executing **/
parseCommand()