Repository navigation
Expand file tree
/
Copy pathhelpers.js
More file actions
81 lines (71 loc) · 2.68 KB
/
Copy pathhelpers.js
File metadata and controls
81 lines (71 loc) · 2.68 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
72
73
74
75
76
77
78
79
80
81
'use strict'
const util = require('util')
const { escape } = require('../../helpers/format')
module.exports = {
/**
* Create an string of given length filled with blank spaces
*
* @param {number} length Length of the array to return
* @return {string}
*/
blankString: function (length) {
return Array.apply(null, new Array(length)).map(String.prototype.valueOf, ' ').join('')
},
/**
* Create a string corresponding to a valid declaration and initialization of an Objective-C object literal.
*
* @param {string} nsClass Class of the litteral
* @param {string} name Desired name of the instance
* @param {Object} parameters Key-value object of parameters to translate to an Objective-C object litearal
* @param {boolean} indent If true, will declare the litteral by indenting each new key/value pair.
* @return {string} A valid Objective-C declaration and initialization of an Objective-C object litteral.
*
* @example
* nsDeclaration('NSDictionary', 'params', {a: 'b', c: 'd'}, true)
* // returns:
* NSDictionary *params = @{ @"a": @"b",
* @"c": @"d" };
*
* nsDeclaration('NSDictionary', 'params', {a: 'b', c: 'd'})
* // returns:
* NSDictionary *params = @{ @"a": @"b", @"c": @"d" };
*/
nsDeclaration: function (nsClass, name, parameters, indent) {
const opening = nsClass + ' *' + name + ' = '
const literal = this.literalRepresentation(parameters, indent ? opening.length : undefined)
return opening + literal + ';'
},
/**
* Create a valid Objective-C string of a literal value according to its type.
*
* @param {*} value Any JavaScript literal
* @return {string}
*/
literalRepresentation: function (value, indentation) {
const join = indentation === undefined ? ', ' : ',\n ' + this.blankString(indentation)
switch (Object.prototype.toString.call(value)) {
case '[object Number]':
return '@' + value
case '[object Array]': {
const valuesRepresentation = value.map(function (v) {
return this.literalRepresentation(v)
}.bind(this))
return '@[ ' + valuesRepresentation.join(join) + ' ]'
}
case '[object Object]': {
const keyValuePairs = []
for (const k in value) {
keyValuePairs.push(util.format('@"%s": %s', k, this.literalRepresentation(value[k])))
}
return '@{ ' + keyValuePairs.join(join) + ' }'
}
case '[object Boolean]':
return value ? '@YES' : '@NO'
default:
if (value === null || value === undefined) {
return ''
}
return '@"' + escape(value.toString(), { delimiter: '"' }) + '"'
}
}
}