import { ARRAY_REPEAT_COUNT_THRESHOLD , ARRAY_REPEAT_MANY_TOKEN , ARRAY_REPEAT_TOKEN , ARRAY_END_TOKEN , ARRAY_START_TOKEN } from "../constants" ; import { Context , InvertedIndex , CompressOptions , Compressors } from "./common" ; import { ZipsonWriter , ZipsonStringWriter } from "./writer" ; import { compressInteger } from "../util" ; import { isObject } from "./util" ; /**
 * Compress array to writer
 */ export function compressArray ( compressors , context , array , invertedIndex , writer , options ) { context . arrayLevel ++ ; if ( context . arrayLevel > context . arrayItemWriters . length ) { context . arrayItemWriters . push ( new ZipsonStringWriter ( ) ) ; } const arrayItemWriter = context . arrayItemWriters [ context . arrayLevel - 1 ] ; const parentWriter = context . arrayItemWriters [ context . arrayLevel - 2 ] || writer ; parentWriter . write ( ARRAY_START_TOKEN ) ; let previousItem = '' ; let repeatedTimes = 0 ; let repeatManyCount = 0 ; let templateObject = new compressors . template . Object ( array [ 0 ] , array [ 1 ] ) ; if ( templateObject . isTemplating ) { templateObject . compressTemplate ( compressors , context , invertedIndex , parentWriter , options ) ; } for ( let i = 0 ; i < array . length ; i ++ ) { let item = array [ i ] ; arrayItemWriter . value = '' ; if ( item === undefined ) { item = null ; } if ( i > 1 && templateObject . isTemplating ) { templateObject . isNextTemplateable ( array [ i ] , parentWriter ) ; } if ( templateObject . isTemplating ) { templateObject . compressTemplateValues ( compressors , context , invertedIndex , arrayItemWriter , options , array [ i ] ) ; } else { compressors . any ( compressors , context , item , invertedIndex , arrayItemWriter , options ) ; } if ( arrayItemWriter . value === previousItem ) { repeatedTimes ++ ; if ( repeatedTimes >= ARRAY_REPEAT_COUNT_THRESHOLD ) { if ( repeatManyCount === 0 ) { parentWriter . write ( ARRAY_REPEAT_MANY_TOKEN ) ; } repeatManyCount ++ ; } else { parentWriter . write ( ARRAY_REPEAT_TOKEN ) ; } } else { repeatedTimes = 0 ; if ( repeatManyCount > 0 ) { parentWriter . write ( compressInteger ( repeatManyCount ) ) ; repeatManyCount = 0 ; } parentWriter . write ( arrayItemWriter . value ) ; previousItem = arrayItemWriter . value ; } } if ( repeatManyCount > 0 ) { parentWriter . write ( compressInteger ( repeatManyCount ) ) ; } if ( templateObject . isTemplating ) { templateObject . end ( parentWriter ) ; } parentWriter . write ( ARRAY_END_TOKEN ) ; context . arrayLevel -- ; }