-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
81 lines (73 loc) · 1.93 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
'use strict';
var assign = require('object-assign');
var msgs = require('./messages.js');
var hasOwnDeep = require('has-own-deep');
var getValue = require('get-value');
var say = require('say');
module.exports = function (opts) {
var defaults = {
voice: null,
messages: msgs,
filters: false
};
if (typeof opts === 'string') {
defaults.messages = opts;
}
var options = assign({}, defaults, opts);
var messages = [];
if (typeof options.messages === 'string') {
messages.push(options.messages);
} else if (Array.isArray(options.messages) || (options.messages instanceof Object)) {
messages = [options.messages];
} else {
throw new TypeError('Expected a string an Array or an Object');
}
// filter and populate messages[]
if (options.filters) {
var filters = options.filters;
if (typeof filters === 'string' && options.messages.hasOwnProperty(filters)) {
messages = options.messages[filters];
} else {
messages = [];
for (var i in filters) {
if ({}.hasOwnProperty.call(filters, i) && hasOwnDeep(options.messages, filters[i])) {
messages.push(getValue(options.messages, filters[i]));
}
}
console.log(messages);
}
}
// flatten an oject to a single level Array.
function flatten(obj) {
var flattened = [];
var maxDepth = 4;
function flatOneLevel(obj, maxDepth, flattened) {
for (var i in obj) {
if ({}.hasOwnProperty.call(obj, i)) {
var item = obj[i];
if (typeof item === 'string') {
flattened.push(item);
} else if (maxDepth > 1) {
flatOneLevel(item, maxDepth - 1, flattened);
}
}
}
}
flatOneLevel(obj, maxDepth, flattened);
return flattened;
}
function getRandomMessage(msgs) {
msgs = flatten(msgs);
if (!msgs || msgs.length === 0) {
return '';
}
return msgs[Math.round(Math.random() * (msgs.length - 1))];
}
var msg = getRandomMessage(messages);
try {
say.speak(options.voice, msg);
return msg;
} catch (err) {
throw err;
}
};