Copy this code and paste it in your HTML
if (!(colName
in colNames
)) colNames
<< colName
}
if (!(rowName
in rowNames
)) rowNames
<< rowName
}
cells.
get( computeKey
(rowName, colName
) ) }
def put
(rowName, colName, value
) { if (!(rowName
in rowNames
)) rowNames
<< rowName
if (!(colName
in colNames
)) colNames
<< colName
endValue
= value.
call(get(rowName, colName
)) }
cells.put(computeKey(rowName, colName), endValue)
}
colNames.
each{colName
-> put
(rowName, colName, value
)} }
}
colNames.
each{colName
-> put
(rowName, colName
){ it
?: value
} } }
}
}
}
def toListOfLists
(withRowNames
=true, withColNames
=true) { def result
= withColNames
? [[topLeft,
*colNames
]] :
[] def row
= withRowNames
? [rowName
] :
[] row
<< get(rowName, colName
) }
result << row
}
result
}
closure.
call(rowName, colName,
get(rowName, colName
)) }
}
}
private computeKey
(rowName, colName
) { [rowName, colName]
}
}
def table
= new Table
(colNames:
['c1',
'c2'], rowNames:
['r1',
'r2'])
void testHasNullAsDefaultCellValue
() { assertNull table.
get('r1',
'c1') }
assertEquals 2, table.rowCount
}
void testCountsColumns
() { assertEquals 2, table.colCount
}
table.addRow('r3')
assertEquals 3, table.rowCount
}
table.addCol('c3')
assertEquals 3, table.colCount
}
void testHasUniqueColumnNames
() { table.addCol('c1')
assertEquals(['c1', 'c2'], table.colNames)
}
void testHasUniqueRowNames
() { table.addRow('r1')
assertEquals(['r1', 'r2'], table.rowNames)
}
void testAddsColumnOnDemand
() { table.put('r1', 'c3', '')
assertEquals(['c1', 'c2', 'c3'], table.colNames)
}
void testAddsRowOnDemand
() { table.put('r3', 'c1', '')
assertEquals(['r1', 'r2', 'r3'], table.rowNames)
}
void testHasNullDefaultValueInCells
() { assertNull table.
get('r1',
'c1') }
void testPutsValueInCell
() { table.put('r1', 'c1', 'value')
assertEquals
'value', table.
get('r1',
'c1') }
void testPutsClosureResultInCell
() { table.put('r1', 'c1', 'value')
table.put('r1', 'c1'){ it + '2'}
assertEquals
'value2', table.
get('r1',
'c1') }
table.fill(1)
assertEquals
( [[1,
1],
[1,
1]], table.
toListOfLists(false,
false) ) }
void testFillsNullCells
() { table.put('r1', 'c1', 2)
table.fillIfNull(1)
assertEquals
( [[2,
1],
[1,
1]], table.
toListOfLists(false,
false) ) }
void testConvertsContentToListOfLists
() { table.put('r1', 'c1', 'r1c1')
table.put('r1', 'c2', 'r1c2')
table.put('r2', 'c1', 'r2c1')
table.put('r2', 'c2', 'r2c2')
table.topLeft = 'x'
assertEquals( [['x', 'c1', 'c2'], ['r1', 'r1c1', 'r1c2'], ['r2', 'r2c1', 'r2c2']], table.toListOfLists() )
}
void testIteratesOverCells
() { table.fill(1)
table.
each{rowName, colName, value
-> result
<< [rowName, colName, value
]} assertEquals( [['r1', 'c1', 1], ['r1', 'c2', 1], ['r2', 'c1', 1], ['r2', 'c2', 1]], result)
}
}