-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·99 lines (83 loc) · 2.44 KB
/
index.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
#!/usr/bin/env node
const chalk = require('chalk');
const program = require('commander');
const request = require('request');
const consoleWidth = () => {
return parseInt(process.stdout.columns);
};
const printResults = (resList) => {
resList.forEach((result) => {
if (typeof (result.definition) !== undefined) {
console.log(chalk.bold.cyan('Word: ') + result.word);
console.log(chalk.bold.cyan('Definition: ') + result.definition);
console.log(chalk.bold.cyan('Score: ') + (result.thumbs_up - result.thumbs_down));
console.log(chalk.bold.green('Ayys: ') + result.thumbs_up + ' | ' + chalk.bold.red('Nayys: ') + result.thumbs_down);
console.log('='.repeat(consoleWidth()));
}
});
};
const getDefinition = (word) => {
const options = {
method: 'GET',
url: 'http://api.urbandictionary.com/v0/define',
qs: {
term: word
},
headers: {
'Cache-Control': 'no-cache',
Accept: 'application/json'
}
};
request(options, function (err, res, body) {
if (err) throw new Error(err);
var trimRes;
const results = JSON.parse(body).list;
const resultsToDisplay = 3;
console.log('='.repeat(consoleWidth()));
if (results.length === 0) {
console.log(chalk.red('No results were found, please try another phrase'));
} else {
if (results.length > resultsToDisplay) {
trimRes = results.slice(0, resultsToDisplay);
} else {
trimRes = results;
}
printResults(trimRes);
}
});
};
program
.version('0.4.3')
.option('-R, --random', 'Display top results for a random word (up to 3), cannot be used when passing a phrase')
.arguments('<phrase>')
.action((slng) => {
getDefinition(slng);
});
program
.on('--help', function () {
console.log('');
console.log(' Examples:');
console.log(' $ slng gucci');
console.log(' $ slng \'square up\'');
console.log('');
});
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}
if(program.random && process.argv.slice(2).length === 1) {
const options = {
method: 'GET',
url: 'http://api.urbandictionary.com/v0/random',
headers: {
'Cache-Control': 'no-cache',
Accept: 'application/json'
}
};
request(options, function (err, res, body) {
const results = JSON.parse(body).list;
const randomWord = results[0].word;
if (err) throw new Error(err);
getDefinition(randomWord);
});
}