Skip to content

Commit 33bf4d7

Browse files
author
João Dias
committed
feat(at): added type safety to return value with generics
1 parent 1fe4db5 commit 33bf4d7

File tree

1 file changed

+12
-9
lines changed
  • src/functions/object

1 file changed

+12
-9
lines changed

src/functions/object/at.ts

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,15 @@ import { isNull } from "../typed";
1818
* at(object, ['a[0].b.c', 'a[1]']);
1919
* // [3, 4]
2020
*/
21-
export function at(object: any, paths: string | string[]): any[] {
22-
const PATHS = Array.isArray(paths) ? paths : [paths];
23-
const FLATTENED_PATHS = flatten(PATHS, 1);
24-
const PATHS_LENGTH = FLATTENED_PATHS.length;
25-
const RESULT = new Array(PATHS_LENGTH);
26-
const SHOULD_SKIP = isNull(object);
21+
export function at<GenericValue>(
22+
object: GenericValue | null | undefined,
23+
paths: string | string[]
24+
): Array<GenericValue[keyof GenericValue]> {
25+
const normalizedPaths = Array.isArray(paths) ? paths : [paths];
26+
const flattenedPaths = flatten(normalizedPaths, 1);
27+
const pathsLength = flattenedPaths.length;
28+
const result = new Array(pathsLength);
29+
const shouldSkip = isNull(object);
2730

2831
/**
2932
* It iterates over the flattenedPaths array.
@@ -32,9 +35,9 @@ export function at(object: any, paths: string | string[]): any[] {
3235
* - If object is null or undefined, it assigns undefined to the result array.
3336
* The get function is used here to safely retrieve nested properties of the object.
3437
*/
35-
for (let index = 0; index < PATHS_LENGTH; index++) {
36-
RESULT[index] = SHOULD_SKIP ? undefined : get(object, FLATTENED_PATHS[index]);
38+
for (let index = 0; index < pathsLength; index++) {
39+
result[index] = shouldSkip ? undefined : get(object, flattenedPaths[index]);
3740
}
3841

39-
return RESULT;
42+
return result;
4043
}

0 commit comments

Comments
 (0)