import { omit } from 'lodash' ; import { Layer , ColorWithLayers } from '../models/color-with-layers.model' ; import { SketchColorMap , SketchColorMapLayer } from '../models/sketch-color-map.model' ; const getChild = ( hierarchy ) : Layer => { if ( hierarchy . length === 1 ) { return hierarchy [ 0 ] ; } return { ... hierarchy [ 0 ] , children : [ getChild ( hierarchy . splice ( 1 ) ) ] , } ; } ; const getHierarchy = ( inputLayer ) : Layer [ ] => { if ( inputLayer . parents . length ) { return [ ... inputLayer . parents , omit ( inputLayer , 'parents' ) ] ; } return [ omit ( inputLayer , 'parents' ) ] ; } ; const mapInputLayerToLayer = ( inputLayer ) : Layer => { const hierarchy = getHierarchy ( inputLayer ) ; return getChild ( hierarchy ) ; } ; const isSketchColorMapLayerType = ( layer ) : layer is SketchColorMapLayer => { return ( < SketchColorMapLayer > layer ) . parents !== undefined ; } ; const addLayerWithGrouping = ( groupedLayers = [ ] , layerToAdd ) : Layer [ ] => { const layer = isSketchColorMapLayerType ( layerToAdd ) ? mapInputLayerToLayer ( layerToAdd ) : layerToAdd ; if ( ! groupedLayers . length ) { return [ layer ] ; } const filteredGroupedLayers = groupedLayers . filter ( groupedLayer => groupedLayer . id === layer . id ) ; if ( filteredGroupedLayers . length ) { return groupedLayers . map ( ( groupedLayer ) => { if ( groupedLayer . name === layer . name && 'children' in layer ) { const updatedLayers = layer . children ! . reduce ( ( acc , cur ) => addLayerWithGrouping ( acc , cur ) , groupedLayer . children ! ) ; return { ... groupedLayer , children : updatedLayers , } ; } return groupedLayer ; } ) ; } return groupedLayers . concat ( [ layer ] ) ; } ; export const transformSketchColorMap = ( colorsObject ) : ColorWithLayers [ ] => { return Object . entries ( colorsObject ) . map ( ( [ color , inputLayers ] ) => ( { color , layers : inputLayers . reduce ( ( acc , cur ) => addLayerWithGrouping ( acc , cur ) , [ ] ) , } ) ) ; } ;