I was recently wokring on building some objects that had this pattern:
const obj = {
startRowIndex: 0,
endRowIndex: 1
}
or
const obj = {
startColumnIndex: 0,
endColumnIndex: 1
}
This object is called a GridRange
in Google's reference documentation.
The above pattern is useful for declaring to the APIs that the values apply to an entire row, or entire column. It's the same as in A1 notation as doing 1:1
or A1:A
.
I considered (for a split second) of using a switch statement, but quickly sought out a more elegant way to code it. Using dynamic properties available in Javascript, one can do this instead:
const type = 'Row';
const obj = {
[`start${type}Index`]: 0,
[`end${type}Index`]: 1
}
That way, I just have to determine if type
is supposed to be equal to "Row"
or "Column"
, which can be done easily enough with an if statement or ternary statement.
It's a syntax that looks strange at first. But if you think of it as being a shortcut for this:
const obj = {};
const start = 'start' + type + 'Index';
const end = 'end' + type + 'Index';
obj[start] = 0;
obj[end] = 1;
The syntax for dyanamic properties makes a lot more sense.
(Dyanmmic properties aren't usually used to replace switch statements; they are more commonly found when using OOP-like solutions in classes, such as [Symbol.*]
etc.)