UNPKG

2.38 kBJavaScriptView Raw
1// // if the variable is defined
2export const exists = what => typeof what !== 'undefined'
3
4// used for JSON object type checking
5const object_constructor = {}.constructor
6
7// detects a JSON object
8export function is_object(object)
9{
10 return exists(object) && (object !== null) && object.constructor === object_constructor
11}
12
13// extends the first object with
14/* istanbul ignore next: some weird transpiled code, not testable */
15export function extend(...objects)
16{
17 const to = objects[0]
18 const from = objects[1]
19
20 if (objects.length > 2)
21 {
22 const last = objects.pop()
23 const intermediary_result = extend.apply(this, objects)
24 return extend(intermediary_result, last)
25 }
26
27 for (let key of Object.keys(from))
28 {
29 if (is_object(from[key]))
30 {
31 if (!is_object(to[key]))
32 {
33 to[key] = {}
34 }
35
36 extend(to[key], from[key])
37 }
38 else
39 {
40 to[key] = from[key]
41 }
42 }
43
44 return to
45}
46
47export function merge()
48{
49 const parameters = Array.prototype.slice.call(arguments, 0)
50 parameters.unshift({})
51 return extend.apply(this, parameters)
52}
53
54export function clone(object)
55{
56 return merge({}, object)
57}
58
59// creates camelCased aliases for all the keys of an object
60export function convert_from_camel_case(object)
61{
62 for (let key of Object.keys(object))
63 {
64 if (/[A-Z]/.test(key))
65 // if (key.indexOf('_') >= 0)
66 {
67 // const camel_cased_key = key.replace(/_(.)/g, function(match, group_1)
68 // {
69 // return group_1.toUpperCase()
70 // })
71
72 // if (!exists(object[camel_cased_key]))
73 // {
74 // object[camel_cased_key] = object[key]
75 // delete object[key]
76 // }
77
78 const lo_dashed_key = key.replace(/([A-Z])/g, function(match, group_1)
79 {
80 return '_' + group_1.toLowerCase()
81 })
82
83 if (!exists(object[lo_dashed_key]))
84 {
85 object[lo_dashed_key] = object[key]
86 delete object[key]
87 }
88 }
89 }
90
91 return object
92}
93
94function escape_regexp(string)
95{
96 const specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", 'g')
97 return string.replace(specials, "\\$&")
98}
99
100export function replace_all(where, what, with_what)
101{
102 const regexp = new RegExp(escape_regexp(what), 'g')
103 return where.replace(regexp, with_what)
104}
105
106export function starts_with(string, substring)
107{
108 return string.indexOf(substring) === 0
109}
110
111export function ends_with(string, substring)
112{
113 const index = string.lastIndexOf(substring)
114 return index >= 0 && index === string.length - substring.length
115}
\No newline at end of file