index.js
1.95 KB
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
'use strict';
const got = require('got');
const uniqueRandomArray = require('unique-random-array');
const EventEmitter = require('eventemitter3');
const randomCache = {};
function formatResult(getRandomImage) {
const imageData = getRandomImage();
if (!imageData) {
return;
}
return `http://imgur.com/${imageData.hash}${imageData.ext.replace(/\?.*/, '')}`;
}
function storeResults(images, subreddit) {
const getRandomImage = uniqueRandomArray(images);
randomCache[subreddit] = getRandomImage;
return getRandomImage;
}
function randomPuppy(subreddit) {
subreddit = (typeof subreddit === 'string' && subreddit.length !== 0) ? subreddit : 'puppies';
if (randomCache[subreddit]) {
return Promise.resolve(formatResult(randomCache[subreddit]));
}
return got(`https://imgur.com/r/${subreddit}/hot.json`, {json: true})
.then(response => storeResults(response.body.data, subreddit))
.then(getRandomImage => formatResult(getRandomImage));
}
// silly feature to play with observables
function all(subreddit) {
const eventEmitter = new EventEmitter();
function emitRandomImage(subreddit) {
randomPuppy(subreddit).then(imageUrl => {
eventEmitter.emit('data', imageUrl + '#' + subreddit);
if (eventEmitter.listeners('data').length) {
setTimeout(() => emitRandomImage(subreddit), 200);
}
});
}
emitRandomImage(subreddit);
return eventEmitter;
}
function callback(subreddit, cb) {
randomPuppy(subreddit)
.then(url => cb(null, url))
.catch(err => cb(err));
}
// subreddit is optional
// callback support is provided for a training exercise
module.exports = (subreddit, cb) => {
if (typeof cb === 'function') {
callback(subreddit, cb);
} else if (typeof subreddit === 'function') {
callback(null, subreddit);
} else {
return randomPuppy(subreddit);
}
};
module.exports.all = all;