1
1
import { State } from '../models/state' ;
2
- import { Actions } from '../features/context' ;
2
+ import { Actions , reducer } from '../features/context' ;
3
3
import { Delimiter } from '../models/delimiter' ;
4
4
import { ColumnsType } from '../models/column' ;
5
5
@@ -16,29 +16,31 @@ const detectDelimiterFromValue = (value: string, defaultDelimiter = Delimiter.CO
16
16
return currentDelimiter ;
17
17
} ;
18
18
19
- const parseData = < T extends { [ key : string ] : string } > (
20
- value : string ,
21
- columns : ColumnsType < T > ,
22
- delimiter : Delimiter
23
- ) => {
19
+ const parseData = < T > ( value : string , columns : ColumnsType < T > , delimiter : Delimiter ) => {
24
20
const lines = value . split ( '\n' ) ;
25
21
return lines . map ( ( line ) => {
26
22
const lineValues = line . split ( delimiter ) ;
27
23
const parsedLine : T = { } as T ;
28
24
columns . forEach ( ( column , columnIndex ) => {
29
- parsedLine [ column . key ] = lineValues [ columnIndex ] as T [ keyof T ] ;
25
+ parsedLine [ column . key ] = ( lineValues [ columnIndex ] as unknown ) as T [ keyof T ] ;
30
26
} ) ;
31
27
return parsedLine ;
32
28
} ) ;
33
29
} ;
34
30
35
- export const SimpleParserMiddleware = < T extends { [ key : string ] : string } > ( state : State < T > , action : Actions ) => {
36
- let newState = state ;
31
+ export const createSimpleParserMiddleware = < T > ( onChange ?: ( value : T [ ] ) => void ) => {
32
+ return ( state : State < T > , action : Actions ) => {
33
+ let newState = reducer < T > ( state , action ) ;
37
34
38
- if ( action . type === 'setRaw' ) {
39
- const delimiter = detectDelimiterFromValue ( action . raw ) ;
40
- newState = { ...newState , parsed : parseData < T > ( action . raw , state . columns , delimiter ) } ;
41
- }
35
+ if ( action . type === 'setRaw' ) {
36
+ const delimiter = detectDelimiterFromValue ( action . raw ) ;
37
+ const parsed = parseData < T > ( action . raw , state . columns , delimiter ) ;
38
+ if ( onChange ) {
39
+ onChange ( parsed ) ;
40
+ }
41
+ newState = { ...newState , parsed } ;
42
+ }
42
43
43
- return newState ;
44
+ return newState ;
45
+ } ;
44
46
} ;
0 commit comments