{"version":3,"file":"index.mjs","names":[],"sources":["../src/get-or-throw.ts"],"sourcesContent":["/**\n * Get a value from an object or array, and throw an error if the key or index\n * does not exist or if the resulting value is undefined.\n *\n * @param objOrArr The object or array to get the value from.\n * @param keyOrIndex The key or index to get the value from.\n * @param errorMessage Optional error message to include in the error thrown.\n * @returns The value at the given key or index, guaranteed to be defined.\n * @throws An error if the key or index does not exist, or if the value is\n *   undefined.\n */\nexport function getOrThrow<T extends object, K extends keyof T>(\n  objOrArr: T,\n  keyOrIndex: K,\n  errorMessage?: string,\n): NonNullable<T[K]>;\nexport function getOrThrow<T>(\n  objOrArr: T[],\n  keyOrIndex: number,\n  errorMessage?: string,\n): T;\nexport function getOrThrow<T extends object, K extends keyof T>(\n  objOrArr: T | T[],\n  keyOrIndex: K | number,\n  errorMessage?: string,\n): T[K] | T {\n  if (Array.isArray(objOrArr)) {\n    const length = objOrArr.length;\n    let index = keyOrIndex as number;\n\n    /** Allow for negative indexing. */\n    if (index < 0) {\n      index = length + index;\n    }\n\n    if (index >= 0 && index < length) {\n      const value = objOrArr[index];\n\n      if (value === undefined) {\n        throw new Error(\n          errorMessage ?? `Value at index ${String(keyOrIndex)} is undefined.`,\n        );\n      }\n      return value;\n    } else {\n      throw new Error(\n        errorMessage ?? `Index ${String(keyOrIndex)} is out of bounds.`,\n      );\n    }\n  } else {\n    if (keyOrIndex in objOrArr) {\n      const value = objOrArr[keyOrIndex as K];\n\n      if (value === undefined) {\n        throw new Error(\n          errorMessage ?? `Value at key \"${String(keyOrIndex)}\" is undefined.`,\n        );\n      }\n      return value;\n    } else {\n      throw new Error(\n        errorMessage ??\n          `Key \"${String(keyOrIndex)}\" does not exist in the object.`,\n      );\n    }\n  }\n}\n\n/** Export the same function under the alias 'got' */\nexport { getOrThrow as got };\n"],"mappings":";AAqBA,SAAgB,WACd,UACA,YACA,cACU;AACV,KAAI,MAAM,QAAQ,SAAS,EAAE;EAC3B,MAAM,SAAS,SAAS;EACxB,IAAI,QAAQ;;AAGZ,MAAI,QAAQ,EACV,SAAQ,SAAS;AAGnB,MAAI,SAAS,KAAK,QAAQ,QAAQ;GAChC,MAAM,QAAQ,SAAS;AAEvB,OAAI,UAAU,KAAA,EACZ,OAAM,IAAI,MACR,gBAAgB,kBAAkB,OAAO,WAAW,CAAC,gBACtD;AAEH,UAAO;QAEP,OAAM,IAAI,MACR,gBAAgB,SAAS,OAAO,WAAW,CAAC,oBAC7C;YAGC,cAAc,UAAU;EAC1B,MAAM,QAAQ,SAAS;AAEvB,MAAI,UAAU,KAAA,EACZ,OAAM,IAAI,MACR,gBAAgB,iBAAiB,OAAO,WAAW,CAAC,iBACrD;AAEH,SAAO;OAEP,OAAM,IAAI,MACR,gBACE,QAAQ,OAAO,WAAW,CAAC,iCAC9B"}