import path from 'path' ; import { exportToFile , getParams , getSourcePaths , loadFile } from './utils' ; import { JSON } from './types' ; if ( require . main === module ) { getJSONTranslations ( ) ; } param sourcePath returns function generateJSONFile ( sourcePath ) { const csv = loadFile ( sourcePath ) as string ; const json = transformToJson ( csv ) ; const outputFile = path . basename ( sourcePath ) . replace ( /\.[^.]+$/ , '.json' ) ; exportToFile ( outputFile , JSON . stringify ( json , null , 2 ) ) ; return json ; } param csv returns function transformToJson ( csv ) { const [ header , ... rows ] = csv . trim ( ) . split ( '\n' ) ; const [ , ... columns ] = header . split ( ';' ) ; return rows . reduce < JSON > ( toMessagesObject ( columns ) , { } ) ; } param devices returns function toMessagesObject ( devices ) { return ( json , row ) => { const [ messageKey , ... deviceMessages ] = row . split ( ';' ) ; return deviceMessages . reduce ( createMessage ( devices , messageKey ) , json ) ; } ; } param devices param messageKey returns function createMessage ( devices , messageKey ) { return ( json , message , index ) => { if ( message ) { const path = [ devices [ index ] , ... messageKey . split ( '.' ) ] ; setProperty ( json , path , message ) ; return json ; } return json ; } ; } param object param path param value function setProperty ( object , [ property , ... remainingProperties ] , value ) { if ( remainingProperties . length === 0 ) { object [ property ] = value ; } else { object [ property ] = object [ property ] ?? { } ; setProperty ( object [ property ] as JSON , remainingProperties , value ) ; } } returns export function getJSONTranslations ( ) { const { sourcePath } = getParams ( ) ; return getSourcePaths ( sourcePath , 'csv' ) . map ( generateJSONFile ) ; }