blob: 5f112626a1ae22693dd824407c2ed8b97f150bc7 [file] [log] [blame]
Matteo Scandolod2044a42017-08-07 16:08:28 -07001
2/*
3 * Copyright 2017-present Open Networking Foundation
4
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8
9 * http://www.apache.org/licenses/LICENSE-2.0
10
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18
Matteo Scandoloa81496a2016-08-16 17:29:42 -070019(function () {
20 angular.module('xos.UITutorial')
21 .service('codeToString', function(){
22 this.toString = code => {
23 if(angular.isArray(code)){
24 return code.map(item => this.toString(item));
25 }
26 else if(angular.isObject(code)){
27 let tmp = {};
28 Object.keys(code).forEach(key => {
29 tmp[key] = this.toString(code[key])
30 });
31 return tmp;
32 }
33 else{
34 return code.toString().split('\n').join('').replace(/ +(?= )/gmi, '');
35 }
36 };
37
38 this.toCode = string => {
39 let code;
40
41 try {
42 code = JSON.parse(string);
43 }
44 catch(e){
45 code = string;
46 }
47
48 if(angular.isArray(code)){
49 return code.map(item => this.toCode(item));
50 }
51 else if(angular.isObject(code)){
52 let tmp = {};
53 Object.keys(code).forEach(key => {
54 tmp[key] = this.toCode(code[key])
55 });
56 return tmp;
57 }
58 else{
59 if(!angular.isNumber(code) && code.indexOf('function') !== -1){
60 try {
61 return function(){
62 // create a closure to host our arguments
63 var func = new Function(`return ${code}`);
64
65 // invoke the original function passing arguments
66 func()(...arguments);
67 }
68 }
69 catch(e){
70 // in this case it is a string
71 return code;
72 }
73 }
74 else if(Number.isNaN(code)){
75 return parseFloat(code);
76 }
77 return code;
78 }
79
80 return code;
81 };
82 });
83})();