import { topToBottomMiddleSortPositions } from "./positionSort" ; import { BoardState , PiecePosition , SortPositionFn } from "./types" ; export const getPiecePosition = ( state , pieceId ) : PiecePosition | null => { const entry = Object . entries ( state . piecePositions ) . find ( ( [ _ , id ] ) => id === pieceId ) ; if ( ! entry ) { return null ; } const [ x , y ] = entry [ 0 ] . split ( "," ) . map ( val => parseInt ( val , 10 ) ) ; return { x , y } ; } ; export const getAllPieces = < TPiece > ( state ) : TPiece [ ] => Object . values ( state . pieces ) . filter ( p => p !== null ) ; export const getPiece = < TPiece > ( state , pieceId ) : TPiece | null => state . pieces [ pieceId ] || null ; export const isBelowPieceLimit = ( state ) => state . pieceLimit === null || getAllPieces ( state ) . length < state . pieceLimit ; export const getPieceForPosition = < TPiece > ( state , x , y ) : TPiece | null => state . pieces [ state . piecePositions [ `${ x },${ y }` ] ] || null ; export const getFirstEmptySlot = ( state , sortPositions = topToBottomMiddleSortPositions ) : ( PiecePosition | null ) => { const emptyPositions = [ ] ; for ( let y = 0 ; y < state . size . height ; y ++ ) { for ( let x = 0 ; x < state . size . width ; x ++ ) { const boardPiece = getPieceForPosition ( state , x , y ) ; if ( ! boardPiece ) { emptyPositions . push ( { x , y } ) ; } } } if ( emptyPositions . length === 0 ) { return null ; } emptyPositions . sort ( sortPositions ) ; const position = emptyPositions [ 0 ] ; return { x : position . x , y : position . y } ; } ;