blob: b8ae242ad05612ffd05021f65d1d12771d0c95dc [file] [log] [blame]
Matteo Scandoloa81496a2016-08-16 17:29:42 -07001(function () {
2 angular.module('xos.UITutorial')
3 .service('codeToString', function(){
4 this.toString = code => {
5 if(angular.isArray(code)){
6 return code.map(item => this.toString(item));
7 }
8 else if(angular.isObject(code)){
9 let tmp = {};
10 Object.keys(code).forEach(key => {
11 tmp[key] = this.toString(code[key])
12 });
13 return tmp;
14 }
15 else{
16 return code.toString().split('\n').join('').replace(/ +(?= )/gmi, '');
17 }
18 };
19
20 this.toCode = string => {
21 let code;
22
23 try {
24 code = JSON.parse(string);
25 }
26 catch(e){
27 code = string;
28 }
29
30 if(angular.isArray(code)){
31 return code.map(item => this.toCode(item));
32 }
33 else if(angular.isObject(code)){
34 let tmp = {};
35 Object.keys(code).forEach(key => {
36 tmp[key] = this.toCode(code[key])
37 });
38 return tmp;
39 }
40 else{
41 if(!angular.isNumber(code) && code.indexOf('function') !== -1){
42 try {
43 return function(){
44 // create a closure to host our arguments
45 var func = new Function(`return ${code}`);
46
47 // invoke the original function passing arguments
48 func()(...arguments);
49 }
50 }
51 catch(e){
52 // in this case it is a string
53 return code;
54 }
55 }
56 else if(Number.isNaN(code)){
57 return parseFloat(code);
58 }
59 return code;
60 }
61
62 return code;
63 };
64 });
65})();