@@ -24,7 +24,7 @@ interface Options {
2424 cache : number ;
2525}
2626
27- //// INTERNAL UTILITY FUNCTIONS ////
27+ //// INTERNAL UTILITIES ////
2828
2929/**
3030 * Returns a numerical representation of an input of unknown type
@@ -167,6 +167,12 @@ const _processOptions = (o?: UserOptions): Options => {
167167 } ;
168168} ;
169169
170+ const _shapeFns = {
171+ circle : _drawCircle ,
172+ square : _drawSquare ,
173+ line : _drawLine ,
174+ } ;
175+
170176//// AVATAR GENERATION PROCEDURE ////
171177
172178const _generate = ( o : Options ) => {
@@ -180,25 +186,24 @@ const _generate = (o: Options) => {
180186 ctx . fillStyle = _pickColor ( o ) ;
181187 ctx . fillRect ( 0 , 0 , o . size , o . size ) ;
182188 // define available draw actions
183- const actions : Array < ( sizeMod : number ) => void > = _shuffle (
184- Object . entries ( {
185- circle : ( sizeMod : number ) => _drawCircle ( ctx , o , sizeMod ) ,
186- square : ( sizeMod : number ) => _drawSquare ( ctx , o , sizeMod ) ,
187- line : ( sizeMod : number ) => _drawLine ( ctx , o , sizeMod ) ,
188- } ) ,
189- o . prng
190- )
191- . filter (
192- ( a , i ) =>
193- ( o . shapes && ! o . shapes . length ) ||
194- ( ! o . shapes && i == 0 ) ||
195- o . shapes ?. includes ( a [ 0 ] as ShapeName )
196- )
197- . map ( ( a ) => a [ 1 ] ) ;
189+ let actions : ( ( ctx : CanvasRenderingContext2D , o : Options , sizeMod ?: number ) => void ) [ ] ;
190+ if ( o . shapes && ! o . shapes . length ) {
191+ // shapes option is an empty array, so all shapes are used
192+ actions = Object . values ( _shapeFns ) ;
193+ } else if ( ! o . shapes ) {
194+ // shapes option is undefined, so pick one random shape to use
195+ const shapeNames : ( keyof typeof _shapeFns ) [ ] = Object . keys (
196+ _shapeFns
197+ ) as ( keyof typeof _shapeFns ) [ ] ;
198+ actions = [ _shapeFns [ shapeNames [ _pickInt ( 0 , shapeNames . length - 1 , o . prng ) ] ] ] ;
199+ } else {
200+ // shapes option is an array of shape names, so use those
201+ actions = o . shapes . map ( ( shape ) => _shapeFns [ shape ] ) ;
202+ }
198203 // draw shapes, count depends on complexity option value, size modifier
199204 // is decreased with each iteration so shapes in the background are bigger
200205 for ( let i = 1 ; i <= o . complexity ; i ++ ) {
201- actions [ i % actions . length ] ( 1.25 - i / o . complexity ) ;
206+ actions [ i % actions . length ] ( ctx , o , 1.25 - i / o . complexity ) ;
202207 }
203208 return canvas . toDataURL ( ) ;
204209} ;
0 commit comments