UNPKG

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