( bracketPathEntries: ReadonlyArray<readonly [bracketPath: string, value: A]> )
| 1865 | * @since 4.0.0 |
| 1866 | */ |
| 1867 | export function makeTreeRecord<A>( |
| 1868 | bracketPathEntries: ReadonlyArray<readonly [bracketPath: string, value: A]> |
| 1869 | ): Schema.TreeRecord<A> { |
| 1870 | const out: any = {} |
| 1871 | const containers = new WeakSet<object>() |
| 1872 | |
| 1873 | function getOrCreateContainer(self: any, key: PropertyKey, shouldBeArray: boolean): any { |
| 1874 | const current = Object.hasOwn(self, key) ? self[key] : undefined |
| 1875 | if (containers.has(current) && Array.isArray(current) === shouldBeArray) { |
| 1876 | return current |
| 1877 | } |
| 1878 | const container = shouldBeArray ? [] : {} |
| 1879 | containers.add(container) |
| 1880 | InternalRecord.assignProperty(self, key, container) |
| 1881 | return container |
| 1882 | } |
| 1883 | |
| 1884 | bracketPathEntries.forEach(([key, value]) => { |
| 1885 | const tokens = bracketPathToTokens(key) |
| 1886 | let cur: any = out |
| 1887 | tokens.forEach((token, i) => { |
| 1888 | const isLast = i === tokens.length - 1 |
| 1889 | |
| 1890 | // We are inside an array and see "[]" (empty token) => append |
| 1891 | if (Array.isArray(cur) && token === "") { |
| 1892 | if (isLast) { |
| 1893 | cur.push(value) |
| 1894 | } else { |
| 1895 | // bracket path: "foo[][bar]" => push a new element and descend into it |
| 1896 | const next = tokens[i + 1] |
| 1897 | const shouldBeArray = typeof next === "number" || next === "" |
| 1898 | const index = cur.length |
| 1899 | cur = getOrCreateContainer(cur, index, shouldBeArray) |
| 1900 | } |
| 1901 | } else if (isLast) { |
| 1902 | // If we're setting a value at a path that already exists |
| 1903 | // convert it to an array to support multiple values for the same key |
| 1904 | const hasOwn = Object.hasOwn(cur, token) |
| 1905 | if (hasOwn && Array.isArray(cur[token])) { |
| 1906 | cur[token].push(value) |
| 1907 | } else if (hasOwn) { |
| 1908 | InternalRecord.assignProperty(cur, token, [cur[token], value]) |
| 1909 | } else { |
| 1910 | InternalRecord.assignProperty(cur, token, value) |
| 1911 | } |
| 1912 | } else { |
| 1913 | const next = tokens[i + 1] |
| 1914 | // if next is a number OR "" (from []), we are building an array |
| 1915 | const shouldBeArray = typeof next === "number" || next === "" |
| 1916 | cur = getOrCreateContainer(cur, token, shouldBeArray) |
| 1917 | } |
| 1918 | }) |
| 1919 | }) |
| 1920 | return out |
| 1921 | } |
| 1922 | |
| 1923 | /** |
| 1924 | * Flattens a nested object into bracket-path entries, filtering leaf values by a type guard. |
no test coverage detected