|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var util = require('util'); |
| 4 | + |
| 5 | +module.exports = { |
| 6 | + /** |
| 7 | + * Create an string of given length filled with blank spaces |
| 8 | + * |
| 9 | + * @param {number} length Length of the array to return |
| 10 | + * @return {string} |
| 11 | + */ |
| 12 | + blankString: function (length) { |
| 13 | + return Array.apply(null, new Array(length)).map(String.prototype.valueOf, ' ').join(''); |
| 14 | + }, |
| 15 | + |
| 16 | + /** |
| 17 | + * Create a string corresponding to a valid NSDictionary declaration and initialization for Objective-C. |
| 18 | + * |
| 19 | + * @param {string} name Desired name of the NSDictionary instance |
| 20 | + * @param {Object} parameters Key-value object of parameters to translate to an Objective-C NSDictionary litearal |
| 21 | + * @param {boolean} indent If true, will declare the NSDictionary litteral by indenting each new key/value pair. |
| 22 | + * @return {string} A valid Objective-C declaration and initialization of an NSDictionary. |
| 23 | + * |
| 24 | + * @example |
| 25 | + * nsDictionaryBuilder('params', {a: 'b', c: 'd'}, true) |
| 26 | + * // returns: |
| 27 | + * NSDictionary *params = @{ @"a": @"b", |
| 28 | + * @"c": @"d" }; |
| 29 | + * |
| 30 | + * nsDictionaryBuilder('params', {a: 'b', c: 'd'}) |
| 31 | + * // returns: |
| 32 | + * NSDictionary *params = @{ @"a": @"b", @"c": @"d" }; |
| 33 | + */ |
| 34 | + nsDictionaryBuilder: function (name, parameters, indent) { |
| 35 | + var dicOpening = 'NSDictionary *' + name + ' = '; |
| 36 | + var dicLiteral = this.literalRepresentation(parameters, indent ? dicOpening.length : null); |
| 37 | + return dicOpening + dicLiteral + ';'; |
| 38 | + }, |
| 39 | + |
| 40 | + /** |
| 41 | + * Create a valid Objective-C string of a literal value according to its type. |
| 42 | + * |
| 43 | + * @param {*} value Any JavaScript literal |
| 44 | + * @return {string} |
| 45 | + */ |
| 46 | + literalRepresentation: function (value, indentation) { |
| 47 | + switch (Object.prototype.toString.call(value)) { |
| 48 | + case '[object Number]': |
| 49 | + return '@' + value; |
| 50 | + case '[object Array]': |
| 51 | + var values_representation = value.map(function (v) { |
| 52 | + return this.literalRepresentation(v); |
| 53 | + }.bind(this)); |
| 54 | + return '@[ ' + values_representation.join(', ') + ' ]'; |
| 55 | + case '[object Object]': |
| 56 | + var keyValuePairs = []; |
| 57 | + for (var k in value) { |
| 58 | + keyValuePairs.push(util.format('@"%s": %s', k, this.literalRepresentation(value[k]))); |
| 59 | + } |
| 60 | + |
| 61 | + var join = indentation === undefined ? ', ' : ',\n ' + this.blankString(indentation); |
| 62 | + |
| 63 | + return '@{ ' + keyValuePairs.join(join) + ' }'; |
| 64 | + default: |
| 65 | + return '@"' + value.replace(/"/g, '\\"') + '"'; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments