Skip to content

Commit c3de3d5

Browse files
author
Flavio Corpa
committed
refactor(list): get rid of as much if statements as possible 🤮
1 parent 4d003e7 commit c3de3d5

File tree

1 file changed

+9
-16
lines changed

1 file changed

+9
-16
lines changed

‎src/list.ts‎

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -157,21 +157,19 @@ class List<T> {
157157
if (index < this.Count() && index >= 0) {
158158
return this._elements[index]
159159
} else {
160-
const MSG =
160+
throw new Error(
161161
'ArgumentOutOfRangeException: index is less than 0 or greater than or equal to the number of elements in source.'
162-
throw new Error(MSG)
162+
)
163163
}
164164
}
165165

166166
/**
167167
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
168168
*/
169169
public ElementAtOrDefault(index: number): T | null {
170-
if (index < this.Count() && index >= 0) {
171-
return this._elements[index]
172-
} else {
173-
return undefined
174-
}
170+
return index < this.Count() && index >= 0
171+
? this._elements[index]
172+
: undefined
175173
}
176174

177175
/**
@@ -217,21 +215,16 @@ class List<T> {
217215
*/
218216
public GroupBy<TResult = T>(
219217
grouper: (key: T) => string | number,
220-
mapper?: (element: T) => TResult
218+
mapper: (element: T) => TResult = val => (val as unknown) as TResult
221219
): { [key: string]: TResult[] } {
222220
const initialValue: { [key: string]: TResult[] } = {}
223-
if (!mapper) {
224-
mapper = val => (val as unknown) as TResult
225-
}
226221
return this.Aggregate((ac, v) => {
227222
const key = grouper(v)
228223
const existingGroup = ac[key]
229224
const mappedValue = mapper(v)
230-
if (existingGroup) {
231-
existingGroup.push(mappedValue)
232-
} else {
233-
ac[key] = [mappedValue]
234-
}
225+
existingGroup
226+
? existingGroup.push(mappedValue)
227+
: (ac[key] = [mappedValue])
235228
return ac
236229
}, initialValue)
237230
}

0 commit comments

Comments
 (0)