1+ import { scriptSectionProcessing } from './common'
2+
3+ class Methods {
4+ constructor ( vueScript = '' ) {
5+ this . methods = this . setMethod ( vueScript )
6+ }
7+ setMethod ( vueScript = '' ) {
8+ let regx = / m e t h o d s \s * : \s * { ( [ ^ ] * ) } / g
9+ let matchMethods = vueScript . match ( regx )
10+ if ( ! matchMethods ) {
11+ let data = scriptSectionProcessing ( vueScript )
12+
13+ vueScript =
14+ data . methodsString . substring ( 0 , data . lastIndex ) +
15+ ',\n methods : {}\n' +
16+ data . methodsString [ data . lastIndex ]
17+ }
18+ let methodsData = this . extractMethodsFromScript ( regx , vueScript )
19+
20+ return methodsData || [ ]
21+
22+ }
23+ extractMethodsFromScript ( regx , vueScript = '' ) {
24+ let { methodsString, firstIndex, lastIndex } = scriptSectionProcessing (
25+ vueScript ,
26+ regx
27+ )
28+ return this . makeArrayOfMethods (
29+ methodsString . substring ( firstIndex + 1 , lastIndex )
30+ )
31+ }
32+
33+ makeArrayOfMethods ( methodsStr ) {
34+ let methodDetails = [ ]
35+ let arrayOfFirstIndexes = [ ]
36+ let arrayOfLastIndexes = [ ]
37+ let bracesStk = [ ]
38+ let fIndex = 0
39+ let lIndex = - 2
40+ var functionName = ''
41+ if ( methodsStr ) {
42+ for ( let i = 0 ; i < methodsStr . length ; i ++ ) {
43+ if ( bracesStk . length === 0 && methodsStr [ i ] === '(' ) {
44+ functionName = methodsStr
45+ . substring ( lIndex + 2 , i )
46+ . split ( '\n' )
47+ . join ( '' )
48+ . split ( ' ' )
49+ . join ( '' )
50+ }
51+ if ( methodsStr [ i ] === '{' ) {
52+ if ( bracesStk . length === 0 ) {
53+ fIndex = i
54+ arrayOfFirstIndexes . push ( fIndex )
55+ }
56+ bracesStk . push ( methodsStr [ i ] )
57+ }
58+ if ( methodsStr [ i ] === '}' ) {
59+ bracesStk . pop ( )
60+ if ( bracesStk . length === 0 ) {
61+ lIndex = i
62+ arrayOfLastIndexes . push ( lIndex )
63+ var obj = {
64+ name : functionName ,
65+ body : methodsStr . substring ( fIndex + 1 , lIndex ) ,
66+ arguments : [ ]
67+ }
68+ methodDetails . push ( obj )
69+ }
70+ }
71+ }
72+ for ( let i = 0 ; i < arrayOfFirstIndexes . length ; i ++ ) {
73+ if ( i == 0 ) {
74+ methodDetails [ i ] . arguments = this . collectArgs (
75+ methodsStr . substring ( 0 , arrayOfFirstIndexes [ i ] )
76+ )
77+ } else {
78+ methodDetails [ i ] . arguments = this . collectArgs (
79+ methodsStr . substring (
80+ arrayOfLastIndexes [ i - 1 ] + 2 ,
81+ arrayOfFirstIndexes [ i ]
82+ )
83+ )
84+ }
85+ }
86+ return methodDetails
87+ }
88+ return [ ]
89+ }
90+ collectArgs ( str ) {
91+ let firstParentheses = null
92+ let lastParentheses = null
93+ for ( let i = 0 ; i < str . length ; i ++ ) {
94+ if ( str [ i ] == '(' ) {
95+ firstParentheses = i
96+ }
97+ if ( str [ i ] == ')' ) {
98+ lastParentheses = i
99+ }
100+ }
101+ return str . substring ( firstParentheses + 1 , lastParentheses ) . split ( ',' )
102+ }
103+ }
104+
105+
106+ export default Methods
0 commit comments