(ast: t.File, key: string)
| 20 | } |
| 21 | |
| 22 | export function getAstByKey(ast: t.File, key: string) { |
| 23 | const programPath = _getProgramNodePath(ast); |
| 24 | if (!programPath) { |
| 25 | return null; |
| 26 | } |
| 27 | |
| 28 | const keyParts = key.split("/").reverse(); |
| 29 | |
| 30 | let result: NodePath = programPath; |
| 31 | |
| 32 | while (true) { |
| 33 | let currentKeyPart = keyParts.pop(); |
| 34 | if (!currentKeyPart) { |
| 35 | break; |
| 36 | } |
| 37 | const isIntegerPart = Number.isInteger(Number(currentKeyPart)); |
| 38 | if (isIntegerPart) { |
| 39 | const maybeBodyItemsArray = result.get("body"); |
| 40 | const bodyItemsArray = Array.isArray(maybeBodyItemsArray) |
| 41 | ? maybeBodyItemsArray |
| 42 | : [maybeBodyItemsArray]; |
| 43 | const index = Number(currentKeyPart); |
| 44 | const subResult = bodyItemsArray[index]; |
| 45 | result = subResult as NodePath; |
| 46 | } else { |
| 47 | const maybeSubResultArray = result.get(currentKeyPart); |
| 48 | const subResultArray = Array.isArray(maybeSubResultArray) |
| 49 | ? maybeSubResultArray |
| 50 | : [maybeSubResultArray]; |
| 51 | const subResult = subResultArray[0]; |
| 52 | result = subResult; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | return result; |
| 57 | } |
| 58 | |
| 59 | function _getProgramNodePath(ast: t.File): NodePath<t.Program> | null { |
| 60 | let result: NodePath<t.Program> | null = null; |
no test coverage detected