-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
80 lines (67 loc) · 1.41 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
/** Safe Firebase keys as it doesn't like ., $, #, [, ], or /. in it's keys
*
* @copyright Copyright (C) 2015 by Yieme
* @module firebase-safekey
*/
(function() {
'use strict';
var _ = require('lodash')
var mapping = {
'.': '<>d',
'$': '<>s',
'#': '<>p',
'[': '<>o',
']': '<>c',
'/': '<>S'
}
var reverse = {}
function reverseMap() {
reverse = {}
_.forEach(mapping, function(n, key) {
reverse[n] = key
})
}
reverseMap()
function config(map) {
map = map || {}
mapping = _.extend(map)
reverseMap()
}
function replaceAll(str, from, to) {
var old = ''
for (var i=0, len=str.length; i < len && old != str; i++) {
old = str
str = str.replace(from, to)
}
return str
}
function applyMap(obj, map) {
if ('string' == typeof obj || 'number' == typeof obj) {
_.forEach(map, function(replace, find) {
obj = replaceAll(obj.toString(), find, replace)
})
return obj
}
var result = {}
for (var i in obj) {
var key = applyMap(i, map)
var value = obj[i]
if (_.isObject(value)) value = applyMap(value, map) // apply to child keys
result[key] = value
}
return result
}
function safeKey(obj, map) {
map = map || mapping
return applyMap(obj, map)
}
function restoreKey(obj, map) {
map = map || reverse
return applyMap(obj, map)
}
module.exports = {
config: config,
safe: safeKey,
restore: restoreKey
}
})();