UNPKG

1.76 kBJavaScriptView Raw
1var charMap = {
2 '?': '.',
3 '\\?': '\\?',
4 '*': '.*',
5 '\\*': '\\*',
6 '^': '\\^',
7 '[^': '[^',
8 '\\[^': '\\[\\^',
9 '$': '\\$',
10 '+': '\\+',
11 '.': '\\.',
12 '(': '\\(',
13 ')': '\\)',
14 '{': '\\{',
15 '}': '\\}',
16 '|': '\\|'
17};
18
19var patternChanger = /\\\?|\?|\\\*|\*|\\\[\^|\[\^|\^|\$|\+|\.|\(|\)|\{|\}|\|/g;
20
21/* Converting pattern into regex */
22exports.patternToRegex = function(pattern) {
23 var fixed = pattern.replace(patternChanger, function(matched) {
24 return charMap[matched]
25 });
26 return new RegExp('^' + fixed + '$');
27}
28
29var mockCallback = exports.mockCallback = function(err, reply) {}; //eslint-disable-line no-empty-function
30
31var parseCallback = exports.parseCallback = function(args) {
32 var callback;
33 var len = args.length;
34 if ('function' === typeof args[len - 1]) {
35 callback = args[len-1];
36 }
37 return callback;
38};
39
40var validKeyType = exports.validKeyType = function(mockInstance, key, type, callback) {
41 if (mockInstance.storage[key] && mockInstance.storage[key].type !== type) {
42 var err = new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
43 mockInstance._callCallback(callback, err);
44 return false;
45 }
46 return true;
47};
48
49var initKey = exports.initKey = function(mockInstance, key, fn) {
50 mockInstance.storage[key] = mockInstance.storage[key] || fn();
51};
52
53var shuffle = exports.shuffle = function(array) {
54 var counter = array.length;
55
56 // While there are elements in the array
57 while (counter > 0) {
58 // Pick a random index
59 var index = Math.floor(Math.random() * counter);
60
61 // Decrease counter by 1
62 counter--;
63
64 // And swap the last element with it
65 var temp = array[counter];
66 array[counter] = array[index];
67 array[index] = temp;
68 }
69
70 return array;
71};