prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
/** See [Enums considered harmful](https://www.youtube.com/watch?v=jjMbPt_H3RQ) for the motivation behind this custom type. (Also worth noting is that in TypeScript 5.0 [all Enums are considered unions](https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#all-enums-are-union-enums).) Similar to [variants](variants.md) for disciminated unions, `enumOf` allows you to more easily and safely create and work with enums in TypeScript. ## Basic Example ```ts export const MyEnum = enumOf( { Dog = "Dog", Cat = "Cat", ZEBRA = 1234, } as const, // the `as const` won't be required in TypeScript 5.0 "MyEnum" // friendly name is optional; used to generate helpful parser errors ) export type MyEnum = EnumOf<typeof MyEnum> // => "Dog" | "Cat" | 1234 ``` ## Methods ### Standard enum-style accessors ```ts const dog = MyEnum.Dog // => "Dog" const zebra = MyEnum.ZEBRA // => 1234 ``` ### Values Access array of all valid values, correctly typed (but without any ordering guarantees). ```ts const myEnumValues = MyEnum.values // => ["Dog", "Cat", 1234] ``` ### Parser Get a safe parser function for this enum automagically! ```ts const parsed = MyEnum.parse("cat") // => a `Result<MyEnum, string>`, in this case `Result.ok("Cat")` ``` ### Match See `match` in the {@link Variants} module docs for more details on matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.match({ Dog: "woof woof", Cat: () => "meow", ZEBRA: "is my skin white with black stripes or black with white stripes??", }) speak(myEnum) ``` ### MatchOrElse See `matchOrElse` in the {@link Variants} module docs for more details on partial matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.matchOrElse({ Dog: "woof woof", Cat: () => "meow", orELse: "I cannot speak.", }) speak(myEnum) ``` @module Enums */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Result } from "./Result" import { String } from "./string" import { Option } from "./Option" import { pipe, flow } from "./Composition" import { Array } from "./Array" import { Identity, NonNullish } from "./prelude" /** @ignore */ type StringKeys<T extends object> = Extract<keyof T, string> /** * A plain object that serves as the definition of the enum type. * Until TypeScript 5.0 is released, you need to specify `as const` * on this object definition. */ type RawEnum = Record<string, string | number> /** @ignore */ type StringKeyValues<T extends RawEnum> = Identity<T[StringKeys<T>]> /** @ignore */ type EnumMatcher<A, R extends RawEnum> = { readonly [Label in StringKeys<R>]: (() => A) | A } /** @ignore */ type PartialEnumMatcher<A, R extends RawEnum> = Partial<EnumMatcher<A, R>> & { readonly orElse: (() => A) | A } type EnumMatch<R extends RawEnum> = <A>( matcher: EnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A type EnumMatchOrElse<R extends RawEnum> = <A>( matcher: PartialEnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A /** * The output of the {@link enumOf} function. Produces an object that serves both as * the enum as well as a namespace for helper functions related to that enum. */ type EnumModule<R extends RawEnum> = Identity< { readonly [Label in StringKeys<R>]: R[Label] } & { /** * Returns a readonly array containing the set of all possible enum values. No * guarantees are made regarding the order of items in the resultant array. */ readonly values: ReadonlyArray<StringKeyValues<R>> /** * For string enum values, the parse function will trim and coerce values to lowercase * before comparison. (This has no effect on numeric enum values.) Thus, if an * enum is defined as `'Yes' | 'No'`, this decoder will parse `'yes'`, `' yES'`, * and `' YES '` correctly into the canonical `'Yes'` enum value. */ readonly parse: (u: unknown) => Result<StringKeyValues<R>, string> /** * Use this function for an exhaustive case check that doesn't require using * a switch/case block or any kind of assertExhaustive check. */ readonly match: EnumMatch<R> /** * Use this function for a partial case check that doesn't require using * a switch/case block. */ readonly matchOrElse: EnumMatchOrElse<R> } > /** * Gets the union type representing all possible enum values. */ export type EnumOf<T> = T extends EnumModule<infer R> ? StringKeyValues<R> : [never, "Error: T must be an EnumModule"] const getParserErrorMessage = <T extends RawEnum>( enumValues: EnumModule<T>["values"], enumFriendlyName: string ) => `Must be an enum value in the set ${enumFriendlyName}{ ${enumValues.join(", ")} }` const toTrimmedLowerCase = (a: string | number) => pipe( Option.some(a), Option.refine(String.isString), Option.map(flow(String.trim, String.toLowerCase)), Option.defaultValue(a) ) const isStringOrNumber = (u: NonNullish): u is string | number => typeof u === "string" || typeof u === "number" const getParseFn = <R extends RawEnum>(enumValues: EnumModule<R>["values"], enumFriendlyName: string) => (u: unknown): Result<StringKeyValues<R>, string> => pipe( Option.ofNullish(u), Result.ofOption( () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } cannot be null/undefined` ), Result.refine( isStringOrNumber, () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } must be a string or number` ), Result.map(toTrimmedLowerCase), Result.bind(testVal => pipe( enumValues,
Array.find(val => toTrimmedLowerCase(val) === testVal), Option.match({
some: a => Result.ok(a), none: () => Result.err( getParserErrorMessage(enumValues, enumFriendlyName) ), }) ) ) ) const isFunc = (f: unknown): f is (...args: any[]) => any => typeof f === "function" const getMatchFn = <R extends RawEnum>(raw: R): EnumMatch<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (!Object.hasOwn(matcher, enumLabel)) { throw new TypeError( `Expected a matcher containing a case for '${enumLabel}'.` ) } const matcherBranch = matcher[enumLabel] return isFunc(matcherBranch) ? matcherBranch() : matcherBranch } const getMatchOrElseFn = <R extends RawEnum>(raw: R): EnumMatchOrElse<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (Object.hasOwn(matcher, enumLabel)) { const branch = matcher[enumLabel] // eslint-disable-next-line @typescript-eslint/no-unsafe-return return isFunc(branch) ? branch() : branch } return isFunc(matcher.orElse) ? matcher.orElse() : matcher.orElse } /** * Generates an "enum module" from a raw object. For motivation behind using a custom * generative function instead of the built-in `enum` types, see [this video](https://youtu.be/jjMbPt_H3RQ). * * This function augments a raw "enum object" with several useful capabilities: `values`, `parse`, `match`, * and `matchOrElse`. * - `values` contains the list of valid enum values * - `parse` is a parser funciton auto-magically created for this enum * - `match` is a pipeable function that allows exhaustive pattern matching * - `matchOrElse` is a pipeable function that allows inexhaustive pattern matching * * @remarks * You can use the `parse` function together with `io-ts` to easily create a decoder for this enum. * * @example * ```ts * export const MyEnum = enumOf({ * Dog = 'Dog', * Cat = 'Cat', * ZEBRA = 1234, * } as const, 'MyEnum') // => friendly name optional; used to generate helpful decoder errors * export type MyEnum = EnumOf<typeof MyEnum>; //=> 'Dog' | 'Cat' | 1234 * * // Standard enum-style accessors * const dog = MyEnum.Dog; // => 'Dog' * const zebra = MyEnum.ZEBRA; // => 1234 * * // Access array of all valid values, correctly typed * const myEnumValues = MyEnum.values; // => ['Dog', 'Cat', 1234] * * // Get a decoder instance for this enum automagically * const myDecoder = MyEnum.decoder; // => a `D.Decoder<unknown, 'Dog' | 'Cat' | 1234>` * * // Match an enum value against all its cases (compiler ensures exhaustiveness) * const value: MyEnum = 'Cat'; * const matchResult = pipe( * value, * MyEnum.match({ * Dog: 'woof woof', * Cat: () => 'meow', * ZEBRA: 'is my skin white with black stripes or black with white stripes??' * }) * ) // => 'meow' * ``` */ export const enumOf = <T extends RawEnum>( raw: T, enumFriendlyName = "" ): EnumModule<T> => { const entriesWithStringKeys = Object.entries(raw).reduce( (acc, [label, value]) => ({ ...acc, [label]: value, }), {} ) const values = Object.values(raw) return { ...entriesWithStringKeys, values, parse: getParseFn(values, enumFriendlyName), match: getMatchFn(raw), matchOrElse: getMatchOrElseFn(raw), } as unknown as EnumModule<T> }
src/Enums.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Option.ts", "retrieved_chunk": " * ) // => \"\"\n */\nexport const defaultWith = <A extends NonNullish>(f: () => A) =>\n match<A, A>({\n some: a => a,\n none: f,\n })\n/**\n * Maps an `Option` using a function that returns another\n * `Option` and flattens the result. Sometimes called `flatMap`.", "score": 0.8083778619766235 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n */\nexport const refine = <A extends NonNullish, B extends A>(f: Refinement<A, B>) =>\n match<A, Option<B>>({\n some: a => (f(a) ? some(a) : none),\n none: none,\n })\n/**\n * Returns the wrapped value if the `Option` is `Some`,\n * otherwise uses the given value as a default value.", "score": 0.7962489128112793 }, { "filename": "src/Map.ts", "retrieved_chunk": " findWithKey(key, equalityComparer),\n Option.match({\n some: ([k, v]) => {\n const copy = new globalThis.Map(map)\n copy.set(k, f(v))\n return copy\n },\n none: map,\n })\n )", "score": 0.7942224740982056 }, { "filename": "src/Result.ts", "retrieved_chunk": " *\n * This API has been optimized for use with left-to-right function composition\n * using `pipe` and `flow`.\n *\n * @example\n * ```\n * pipe(\n * Result.tryCatch(() => readFileMightThrow()),\n * Result.mapErr(FileError.create),\n * Result.bind(fileText => pipe(", "score": 0.7919259071350098 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n * pipe(\n * 56,\n * Option.ofNullish,\n * Option.filter(n => n > 50),\n * Option.map(String),\n * Option.match({\n * some: a => `${a}!`,\n * none: \"!\"\n * }),", "score": 0.7890738248825073 } ]
typescript
Array.find(val => toTrimmedLowerCase(val) === testVal), Option.match({
/** * The string module is a suite of functions that are useful for string manipulation and * properly, designed for seamless use in function composition pipelines. * * @module String */ import { NonEmptyArray } from "./NonEmptyArray" /** * A boolean check that also serves as a type guard which narrows the * type to the string literal `""`. * * @group Utils * @group Type Guards * * @returns boolean */ export const isEmpty = (s: string): s is "" => s === "" /** * Curried version of the built-in trim method. * * @group Utils */ export const trim = (s: string) => s.trim() /** * Curried version of the built-in toLowerCase method. * * @group Utils */ export const toLowerCase = (s: string) => s.toLowerCase() /** * Curried version of the built-in toUpperCase method. * * @group Utils */ export const toUpperCase = (s: string) => s.toUpperCase() /** * Type guard that holds true when `u` is a string. * * @group Type Guards * * @returns boolean */ export const isString = (u: unknown): u is string => typeof u === "string" /** * Get the length of a string. * * @group Utils */ export const length = (s: string) => s.length /** * Reverses a string. * * @group Utils */ export const reverse = (s: string) => s.split("").reverse().join("") /** * A curried version of the built-in split method that * is guaranteed to always return at least one entry. If * the split fails to produce at least one entry, the entire * input string is returned as a single-element array. * * @group Utils */ export const split = (separator: string | RegExp) =>
(s: string): NonEmptyArray<string> => {
const result = s.split(separator) return result.length > 0 ? (result as unknown as NonEmptyArray<string>) : [s] } /** * Capitalize the first letter of a string. * * @group Utils */ export const capitalize = (s: string) => { if (s.length < 1) { return "" } const [head, ...tail] = s.split("") return [head.toUpperCase(), ...tail].join("") } /** * Uncapitalize the first letter of a string. * * @group Utils */ export const uncapitalize = (s: string) => { if (s.length < 1) { return "" } const [head, ...tail] = s.split("") return [head.toLowerCase(), ...tail].join("") } /* c8 ignore start */ /** @ignore */ export const String = { isEmpty, trim, toLowerCase, toUpperCase, isString, split, length, reverse, capitalize, uncapitalize, } /* c8 ignore end */
src/string.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Array.ts", "retrieved_chunk": " * @group Type Guards\n * @group Utils\n */\nexport const isNonEmpty = <A>(as: readonly A[]): as is NonEmptyArray<A> => as.length > 0\n/**\n * Also commonly known as `flatMap`. Maps each element of the array\n * given a function that itself returns an array, then flattens the result.\n *\n * @group Mapping\n *", "score": 0.9133555889129639 }, { "filename": "src/NonEmptyArray.ts", "retrieved_chunk": " * Constructs a new non-empty array containing exactly one element.\n *\n * @group Constructors\n */\nexport const of = <A>(a: A): NonEmptyArray<A> => [a]\n/**\n * Create a new array by enumerating the integers between\n * the given start and end, inclusive of both start and end.\n *\n * Both start and end are normalized to integers, and end is", "score": 0.9130831956863403 }, { "filename": "src/Array.ts", "retrieved_chunk": " (as: readonly A[]): NonEmptyArray<A> =>\n [a, ...as]\n/**\n * Return a Map of keys to groups, where the selector function\n * is used to generate a string key that determines in which group\n * each array element is placed.\n *\n * @group Grouping\n * @group Utils\n *", "score": 0.9117056727409363 }, { "filename": "src/Map.ts", "retrieved_chunk": "/**\n * Get the first key for which the given predicate function returns\n * true, wrapped in a `Some`. If no key is found, returns `None`. Uses\n * the given `OrderingComparer` if passed, otherwise defaults to default\n * ASCII-based sort.\n *\n * @group Lookups\n */\nexport const findKey =\n <K extends NonNullish>(", "score": 0.9049180746078491 }, { "filename": "src/Result.ts", "retrieved_chunk": " }\n }\n/* eslint-disable func-style */\n/**\n * Attempts to invoke a function that may throw. If the function\n * succeeds, returns an Ok with the result. If the function throws,\n * returns an Err containing the thrown Error, optionally transformed.\n *\n * @group Utils\n *", "score": 0.9035841822624207 } ]
typescript
(s: string): NonEmptyArray<string> => {
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else if (isErr(results[1])) { return err(results[1].err) } else { return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) =>
Option.match<A, Result<A, E>>({
some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => { if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/AsyncResult.ts", "retrieved_chunk": " */\nexport const ok =\n <A, E = never>(ok: A): AsyncResult<A, E> =>\n () =>\n Promise.resolve(Result.ok(ok))\n/**\n * Construct a new `Err` instance.\n *\n * @group Constructors\n *", "score": 0.8900327682495117 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n */\nexport const refine = <A extends NonNullish, B extends A>(f: Refinement<A, B>) =>\n match<A, Option<B>>({\n some: a => (f(a) ? some(a) : none),\n none: none,\n })\n/**\n * Returns the wrapped value if the `Option` is `Some`,\n * otherwise uses the given value as a default value.", "score": 0.8725011944770813 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": " * @returns A new `AsyncResult` using the given err value.\n */\nexport const err =\n <E, A = never>(err: E): AsyncResult<A, E> =>\n () =>\n Promise.resolve(Result.err(err))\n/**\n * Maps the wrapped `Ok` value using the given function and\n * returns a new `AsyncResult`. Passes `Err` values through as-is.\n *", "score": 0.8721761703491211 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ) // => \"\"\n */\nexport const defaultWith = <A extends NonNullish>(f: () => A) =>\n match<A, A>({\n some: a => a,\n none: f,\n })\n/**\n * Maps an `Option` using a function that returns another\n * `Option` and flattens the result. Sometimes called `flatMap`.", "score": 0.8709244728088379 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": " */\nexport interface AsyncResult<A, E> {\n (): Promise<Result<A, E>>\n}\n/**\n * Construct a new `Ok` instance.\n *\n * @group Constructors\n *\n * @returns A new `AsyncResult` containing the given ok value.", "score": 0.8694406151771545 } ]
typescript
Option.match<A, Result<A, E>>({
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else if (isErr(results[1])) { return err(results[1].err) } else { return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => { if (isErr(
r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) {
return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Nullable.ts", "retrieved_chunk": " * equals(4, 4) // => true\n * equals(4, 5) // => false\n * ```\n */\nexport const getEqualityComparer = <A extends NonNullish>(\n equalityComparer: EqualityComparer<A>\n) =>\n EqualityComparer.ofEquals<Nullable<A>>(\n (a1, a2) =>\n (a1 == null && a2 == null) ||", "score": 0.8631256818771362 }, { "filename": "src/NonEmptyArray.ts", "retrieved_chunk": " * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison.\n *\n * @returns A new `EqualityComparer` instance\n */\nexport const getEqualityComparer = <A>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<NonEmptyArray<A>> =>\n EqualityComparer.ofEquals((arr1, arr2) => {", "score": 0.8624411225318909 }, { "filename": "src/Array.ts", "retrieved_chunk": " * const eq = Array.getEqualityComparer(EqualityComparer.Number)\n * eq.equals([1, 2, 3], [1, 2, 3]) // => true\n * eq.equals([1, 3], [3, 1]) // => false\n */\nexport const getEqualityComparer = <A>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<readonly A[]> =>\n EqualityComparer.ofEquals((arr1, arr2) => {\n if (isEmpty(arr1) && isEmpty(arr2)) {\n return true", "score": 0.8524956107139587 }, { "filename": "src/Option.ts", "retrieved_chunk": "export const getEqualityComparer = <A extends NonNullish>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<Option<A>> =>\n // `ofEquals` has a built-in reference equality check, which captures the None/None case\n EqualityComparer.ofEquals((opt1, opt2) =>\n pipe(\n [opt1, opt2] as const,\n map2((a1: A, a2: A) => equals(a1, a2)),\n defaultValue(false)\n )", "score": 0.8463188409805298 }, { "filename": "src/EqualityComparer.ts", "retrieved_chunk": " * @returns A new `EqualityComparer` instance.\n */\nexport const ofStruct = <A extends object>(\n struct: EqualityComparerRecord<A>\n): EqualityComparer<Readonly<A>> =>\n ofEquals((a1, a2) => {\n for (const key in struct) {\n if (!struct[key].equals(a1[key], a2[key])) {\n return false\n }", "score": 0.8434702157974243 } ]
typescript
r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) {
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else if (isErr(results[1])) { return
err(results[1].err) } else {
return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => { if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Array.ts", "retrieved_chunk": " */\nexport const chooseR =\n <A, E, B>(f: (a: A) => Result<B, E>) =>\n (as: readonly A[]): readonly B[] => {\n const bs: B[] = []\n for (let i = 0; i < as.length; i++) {\n const result = f(as[i])\n if (Result.isOk(result)) {\n bs.push(result.ok)\n }", "score": 0.8185566067695618 }, { "filename": "src/Option.ts", "retrieved_chunk": " (options: readonly [Option<A>, Option<B>]): Option<C> => {\n if (isSome(options[0]) && isSome(options[1])) {\n return some(map(options[0].some, options[1].some))\n }\n return none\n }\n/**\n * Returns a Some containing the value returned from the map function\n * if all three `Option`s are `Some`s. Otherwise, returns `None`.\n *", "score": 0.7834179997444153 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": "export const mapBoth =\n <A1, A2, E1, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) =>\n (async: AsyncResult<A1, E1>) =>\n () =>\n async().then(Result.mapBoth(mapOk, mapErr))\n/**\n * Maps the wrapped `Ok` value using a given function that\n * also returns an AsyncResult, and flattens the result.\n * Also commonly known as `flatpMap`.\n *", "score": 0.782591700553894 }, { "filename": "src/Option.ts", "retrieved_chunk": " <\n A extends NonNullish,\n B extends NonNullish,\n C extends NonNullish,\n D extends NonNullish\n >(\n map: (a: A, b: B, c: C) => D\n ) =>\n (options: readonly [Option<A>, Option<B>, Option<C>]): Option<D> => {\n if (isSome(options[0]) && isSome(options[1]) && isSome(options[2])) {", "score": 0.769298791885376 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " return getMatcherResult(matcher.inProgress, undefined)\n case \"NotStarted\":\n return getMatcherResult(matcher.notStarted, undefined)\n case \"Resolved\":\n return pipe(\n deferredResult.resolved,\n Result.match({\n ok: a => getMatcherResult(matcher.resolvedOk, a),\n err: e => getMatcherResult(matcher.resolvedErr, e),\n })", "score": 0.7682774066925049 } ]
typescript
err(results[1].err) } else {
/** * A suite of useful functions for working with readonly arrays. These functions * provide a curried API that works seamlessly with right-to-left function * composition and preserve the `readonly` type. * * @module Array */ import { Predicate, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { Result } from "./Result" import { pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" import { OrderingComparer } from "./OrderingComparer" import { NonEmptyArray } from "./NonEmptyArray" /* eslint-disable func-style */ /** * Curried and readonly version of the built-in `filter`. * Accepts a plain predicate function or a refinement * function (a.k.a. type guard). * * @group Filtering */ export function filter<A, B extends A>( refinement: Refinement<A, B> ): (as: readonly A[]) => readonly B[] export function filter<A>( predicate: Predicate<A> ): <B extends A>(bs: readonly B[]) => readonly B[] export function filter<A>(predicate: Predicate<A>): (as: readonly A[]) => readonly A[] export function filter<A>(f: Predicate<A>) { return <B extends A>(as: readonly B[]) => as.filter(f) } /* eslint-enable func-style */ /** * Like {@link filter}, but the predicate function also accepts the * index of the element as an argument. * * @group Filtering */ export const filteri = <A>(f: (a: A, i: number) => boolean) => (as: readonly A[]): readonly A[] => as.filter(f) /** * Curried and readonly version of the built-in `map`. * * @group Mapping */ export const map = <A, B>(f: (a: A) => B) => (as: readonly A[]): readonly B[] => as.map(f) /** * Like {@link map} but the map function also accepts the * index of the element as an argument. * * @group Mapping */ export const mapi = <A, B>(f: (a: A, i: number) => B) => (as: readonly A[]): readonly B[] => as.map(f) /** * Maps each value of the array into an `Option`, and keeps only the inner * values of those `Option`s that are`Some`. Essentially, this is a combined map + * filter operation where each element of the array is mapped into an `Option` * and an `isSome` check is used as the filter function. * * @group Mapping * * @example * pipe( * [32, null, 55, undefined, 89], // (number | null | undefined)[] * Array.choose(x => pipe( * x, // number | null | undefined * Option.ofNullish, // Option<number> * Option.map(String) // Option<string> * )) // string[] * ) // => ["32", "55", "89"] */ export const choose = <A, B extends NonNullish>(f: (a: A) => Option<B>) => (as: readonly A[]): readonly B[] => { const bs: B[] = [] for (let i = 0; i < as.length; i++) { const maybeB = f(as[i])
if (Option.isSome(maybeB)) {
bs.push(maybeB.some) } } return bs } /** * Like {@link choose}, but maps each value of the array into a `Result`, * and keeps only the values where the projection returns `Ok`. Essentially, * this is a combined map + filter operation where each element of the array * is mapped into an `Result` and an `isOk` check is used as the filter function. * * @group Mapping * * @example * pipe( * [32, null, 55, undefined, 89], // (number | null | undefined)[] * Array.chooseR(x => pipe( * x, // number | null | undefined * Option.ofNullish, // Option<number> * Option.map(String), // Option<string> * Result.ofOption(() => "err") // Result<string, string> * )) // string[] * ) // => ["32", "55", "89"] */ export const chooseR = <A, E, B>(f: (a: A) => Result<B, E>) => (as: readonly A[]): readonly B[] => { const bs: B[] = [] for (let i = 0; i < as.length; i++) { const result = f(as[i]) if (Result.isOk(result)) { bs.push(result.ok) } } return bs } /** * Get the first element of the array (wrapped in `Some`) if * non-empty, otherwise `None`. * * @group Utils * @group Pattern Matching * * @example * ```ts * Array.head([]) // => `Option.none` * Array.head([1, 2, 3]) // => `Option.some(1)` * ``` */ export const head = <A extends NonNullish>(as: readonly A[]): Option<A> => as.length > 0 ? Option.some(as[0]) : Option.none /** * Alias of {@link head}. * * @group Utils * @group Pattern Matching */ export const first = head /** * Get a new array containing all values except the first * one (wrapped in `Some`) if non-empty, otherwise `None`. * * @group Utils * @group Pattern Matching * * @example * pipe( * [1, 2, 3, 4], * Array.tail * ) // => Option.some([2, 3, 4]) */ export const tail = <A>(as: readonly A[]): Option<readonly A[]> => { if (as.length === 0) { return Option.none } // eslint-disable-next-line @typescript-eslint/no-unused-vars const [_, ...tail] = as return Option.some(tail) } /** * Get the first `n` elements of the array. Will return the entire * array if `n` is greater than the length of the array. * * @param count is normalized to a non-negative integer * * @group Utils * * @example * pipe( * [1, 2, 3, 4, 5, 6], * Array.take(3) * ) // => [1, 2, 3] */ export const take = (count: number) => <A>(as: readonly A[]): readonly A[] => { const c = count <= 0 ? 0 : Math.floor(count) if (c > as.length) { return as } const out: A[] = [] for (let i = 0; i < as.length && i < c; i++) { out.push(as[i]) } return out } /** * Get the remaining elements of the array * after skipping `n` elements. Returns empty if the * skip count goes past the end of the array. * * @group Utils * * @param count is normalized to a non-negative integer * * @example * pipe( * [1, 2, 3, 4, 5, 6], * Array.skip(3) * ) // => [4, 5, 6] */ export const skip = (count: number) => <A>(as: readonly A[]): readonly A[] => { const c = count <= 0 ? 0 : Math.floor(count) if (c >= as.length) { return [] } const out: A[] = [] for (let i = c; i < as.length; i++) { out.push(as[i]) } return out } /** * Curried and readonly version of the built-in `Array.prototype.reduce`. Takes * the initial value first instead of last. * * @group Utils * @group Folding */ export const reduce = <A, B>(initialValue: B, reducer: (acc: B, next: A) => B) => (as: readonly A[]): B => as.reduce(reducer, initialValue) /** * Curried and readonly version of the built-in `Array.prototype.reduceRight`. * Takes the initial value first instead of last. * * @group Utils * @group Folding */ export const reduceRight = <A, B>(initialValue: B, reducer: (acc: B, next: A) => B) => (as: readonly A[]): B => as.reduceRight(reducer, initialValue) const isRawValue = <A, R>(caseFn: R | ((ok: A) => R)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * @ignore */ interface ArrayMatcher<A, R> { empty: (() => R) | R nonEmpty: ((as: NonEmptyArray<A>) => R) | R } /** * Exhaustive pattern match against an array to "unwrap" its values. Provide * a matcher object to handle both the `empty` and `nonEmpty` cases. * The matcher can use lambdas or raw values. In the `nonEmpty` case, * the lambda will be given a `NonEmptyArray`. * * @group Pattern Matching * * @example * ```ts * pipe( * ["a", "b"], * Array.match({ * empty: () => "default", * nonEmpty: Array.reduceRight("", (a, b) => `${a}${b}`) * }) * ) // => "ba" * ``` */ export const match = <A, R>(matcher: ArrayMatcher<A, R>) => (as: readonly A[]): R => as.length > 0 ? getMatcherResult(matcher.nonEmpty, as as NonEmptyArray<A>) : getMatcherResult(matcher.empty, undefined) /** * Type guard that tests whether the given array is equivalent * to the empty tuple type. * * @group Type Guards * @group Utils */ export const isEmpty = <A>(as: readonly A[]): as is readonly [] => as.length === 0 /** * Type guard that tests whether the given array is a `NonEmptyArray` * * @group Type Guards * @group Utils */ export const isNonEmpty = <A>(as: readonly A[]): as is NonEmptyArray<A> => as.length > 0 /** * Also commonly known as `flatMap`. Maps each element of the array * given a function that itself returns an array, then flattens the result. * * @group Mapping * * @example * pipe( * [1, 2, 3], * Array.bind(n => [n, n]) * ) // => [1, 1, 2, 2, 3, 3] */ export const bind = <A, B>(f: (a: A) => readonly B[]) => (as: readonly A[]): readonly B[] => as.flatMap(f) /** * Alias of {@link bind}. * * @group Mapping */ export const flatMap = bind /** * Add an element to the _end_ of an array. Always returns * a `NonEmptyArray`. * * @group Utils */ export const append = <A>(a: A) => (as: readonly A[]): NonEmptyArray<A> => [...as, a] as unknown as NonEmptyArray<A> /** * Also known as `cons`. Insert an element at the beginning * of an array. Always returns a `NonEmptyArray`. * * @group Utils * * @example * pipe( * [2, 3], * Array.prepend(1) * ) // => [1, 2, 3] */ export const prepend = <A>(a: A) => (as: readonly A[]): NonEmptyArray<A> => [a, ...as] /** * Return a Map of keys to groups, where the selector function * is used to generate a string key that determines in which group * each array element is placed. * * @group Grouping * @group Utils * * @example * pipe( * [1, 2, 1, 2, 3, 3, 5], * Array.groupBy(String) * ) * // structurally equivalent to * new Map([ * ['1', [1, 1]], * ['2', [2, 2]], * ['3', [3, 3]], * ['5', [5]] * ]) */ export const groupBy = <A>(selector: (a: A) => string) => (as: readonly A[]): ReadonlyMap<string, NonEmptyArray<A>> => { const groups: Map<string, NonEmptyArray<A>> = new Map() as.forEach(a => { const key = selector(a) return groups.has(key) ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion groups.set(key, pipe(groups.get(key)!, append(a))) : groups.set(key, [a]) }) return groups } /** * Add an array of values to the _end_ of the subsequently * passed (partially applied) array, in a way that makes sense * when reading top-to-bottom/left-to-right using `pipe`. * * @group Utils * * @example * pipe( * [1, 2], * Array.concat([3, 4]) * ) // => [1, 2, 3, 4] */ export const concat = <A>(addToEnd: readonly A[]) => (as: readonly A[]): readonly A[] => [...as, ...addToEnd] /** * Like {@link concat}, except this adds an array of values to the * _beginning_ of the subsequently (partially applied) array, * in a way that makes more sense when _not_ using `pipe`. * * @group Utils * * @example * ```ts * // Reads "backwards" when used with `pipe` * pipe( * ["a", "b"], * Array.concatFirst(["c", "d"]) * ) // => ["c", "d", "a", "b"] * // Reads better when *not* used with `pipe` * Array.concatFirst(["a", "b"])(["c", "d"]) // => ["a", "b", "c", "d"] * ``` */ export const concatFirst = <A>(addToFront: readonly A[]) => (as: readonly A[]): readonly A[] => [...addToFront, ...as] /** * Returns true if at least one element of the array * satisfies the given predicate. Curried version of * `Array.prototype.some`. * * @group Utils */ export const exists = <A>(predicate: (a: A) => boolean) => (as: readonly A[]): boolean => as.some(predicate) /** * Alias of {@link exists}. * * @group Utils */ export const some = exists /** * Equivalent to calling `Array.prototype.flat()` with a depth of 1. * * @group Utils */ export const flatten = <A>(as: readonly (readonly A[])[]): readonly A[] => as.flat() /** * Split an array into chunks of a specified size. The final * chunk will contain fewer elements than the specified size if * the array is not evenly divisible by the specified size. * * @remarks * **Note:** Will return `[]`, _not_ `[[]]` if given an empty array. * * @param maxChunkSize Normalized to a positive integer. * * @example * pipe( * ["a", "b", "c", "d", "e"], * Array.chunk(2) * ) // => [["a", "b"], ["c", "d"], ["e"]] * * @group Utils * @group Grouping */ export const chunk = (maxChunkSize: number) => <A>(as: readonly A[]): readonly NonEmptyArray<A>[] => { if (isEmpty(as)) { return [] } const chunkSize = maxChunkSize <= 1 ? 1 : Math.floor(maxChunkSize) const numChunks = Math.ceil(as.length / chunkSize) // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const chunks: A[][] = [...globalThis.Array(numChunks)].map(() => []) let chunkIndex = 0 for (let i = 0; i < as.length; i++) { if (i !== 0 && i % chunkSize === 0) { chunkIndex++ } chunks[chunkIndex].push(as[i]) } return chunks as unknown as readonly NonEmptyArray<A>[] } /** * Get the length of an array. * * @group Utils */ export const length = <A>(as: readonly A[]) => as.length /** * Returns true if the given element is in the array. * Optionally, pass an `EqualityComparer` to use. Uses * reference (triple equals) equality by default. * * @group Utils */ export const contains = <A>(a: A, equalityComparer: EqualityComparer<A> = EqualityComparer.Default) => (as: readonly A[]): boolean => { if (isEmpty(as)) { return false } const predicate = (test: A) => equalityComparer.equals(a, test) return as.some(predicate) } /** * Return a new array containing only unique values. If * passed, uses the `EqualityComparer` to test uniqueness. * Defaults to using reference equality (triple equals). * * @group Utils * * @example * pipe( * [3, 2, 1, 2, 1, 4, 9], * Array.uniq() * ) // => [3, 2, 1, 4, 9] */ export const uniq = <A>(equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } const out: A[] = [] as.forEach(a => { if (!contains(a, equalityComparer)(out)) { out.push(a) } }) return out } /** * Returns a new array containing only unique values as determined * by mapping each element with the given function and optionally * passing an equality comparer to use on the mapped elements. * Defaults to using reference equality (triple equals). * * @group Utils * * @example * pipe( * [{ name: "Rufus" }, { name: "Rex" }, { name: "Rufus" }], * Array.uniqBy(p => p.name) * ) // => [{ name: "Rufus" }, { name: "Rex" }] */ export const uniqBy = <A, B>(f: (a: A) => B, equalityComparer?: EqualityComparer<B>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } const out: A[] = [] const projections: B[] = [] as.forEach(a => { const projected = f(a) if (!contains(projected, equalityComparer)(projections)) { projections.push(projected) out.push(a) } }) return out } /** * Get a new array with elements sorted. If given, will use the * `OrderingComparer`. Otherwise, uses the default JavaScript ASCII-based sort. * * @group Utils * * @example * declare const petByNameComparer: OrderingComparer<Pet> * * const pets: readonly Pet[] = [ * { name: "Fido" }, * { name: "Albus" }, * { name: "Rex" }, * { name: "Gerald" } * ] * * pipe( * pets, * Array.sort(petByNameComparer), * Array.map(p => p.name) * ) // => [ "Albus", "Fido", "Gerald", "Rex" ] */ export const sort = <A>(orderingComparer?: OrderingComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } return as.slice(0).sort(orderingComparer?.compare) } /** * Get a new array with elements sorted based on the sort-order * of each mapped element produced by the given mapping function. * If given, will use the `OrderingComparer`. Otherwise, defaults to an * OrderingComparer that `String`s the mapped element and uses the * default ASCII-based sort. * * @group Utils */ export const sortBy = <A, B>( f: (a: A) => B, orderingComparer: OrderingComparer<B> = OrderingComparer.Default ) => (as: readonly A[]): readonly A[] => isEmpty(as) ? [] : as.slice(0).sort((o1: A, o2: A) => orderingComparer.compare(f(o1), f(o2))) /** * Get a new array with the elements in reverse order. * * @group Utils */ export const reverse = <A>(as: readonly A[]): readonly A[] => as.slice(0).reverse() /** * Get the _first_ element in the array (wrapped in a `Some`) that * returns `true` for the given predicate, or `None` if no such * element exists. * * @group Utils */ export const find = <A extends NonNullish>(predicate: Predicate<A>) => (as: readonly A[]): Option<A> => Option.ofNullish(as.find(predicate)) /** * Get the _first_ index of the array (wrapped in a `Some`) for * which the element at that index returns true for the given predicate, * or `None` if no such index/element exists. * * @group Utils */ export const findIndex = <A>(predicate: Predicate<A>) => (as: readonly A[]): Option<number> => { const result = as.findIndex(predicate) return result < 0 ? Option.none : Option.some(result) } /** * Get a new array containing only those elements that are not * in the given `excludeThese` array. If given, will use the * EqualityComparer. Otherwise, defaults to reference equality * (triple equals). * * @group Utils * * @example * pipe( * [1, 2, 3, 4, 5], * Array.except([2, 5]) * ) // => [1, 3, 4] */ export const except = <A>(excludeThese: readonly A[], equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } if (isEmpty(excludeThese)) { return as } const out: A[] = [] for (let i = 0; i < as.length; i++) { if (!pipe(excludeThese, contains(as[i], equalityComparer))) { out.push(as[i]) } } return out } /** * Get a new array containing the set union of two arrays, defined as the * set of elements contained in both arrays. **Remember:** sets only contain * unique elements. If you just need to join two arrays together, use {@link concat}. * * @group Utils */ export const union = <A>(unionWith: readonly A[], equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => isEmpty(unionWith) && isEmpty(as) ? [] : pipe(as, concat(unionWith), uniq(equalityComparer)) /** * Get an {@link EqualityComparer} that represents structural equality for an array * of type `A` by giving this function an `EqualityComparer` for each `A` element. * * @group Equality * @group Utils * * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison. * * @returns A new `EqualityComparer` instance * * @example * const eq = Array.getEqualityComparer(EqualityComparer.Number) * eq.equals([1, 2, 3], [1, 2, 3]) // => true * eq.equals([1, 3], [3, 1]) // => false */ export const getEqualityComparer = <A>({ equals, }: EqualityComparer<A>): EqualityComparer<readonly A[]> => EqualityComparer.ofEquals((arr1, arr2) => { if (isEmpty(arr1) && isEmpty(arr2)) { return true } if (arr1.length !== arr2.length) { return false } for (let i = 0; i < arr1.length; i++) { if (!equals(arr1[i], arr2[i])) { return false } } return true }) /** * Does not affect the passed array at runtime. (Effectively executes an identity * function) Removes the `readonly` part of the **type** only. * * @group Utils */ export const asMutable = <A>(as: readonly A[]) => as as A[] /** * Execute an arbitrary side effect for each element of the array. Essentially a * curried version of the built-in `forEach` method. * * @group Utils */ export const iter = <A>(f: (a: A) => void) => (as: readonly A[]): void => as.forEach(a => f(a)) /** @ignore */ export const Array = { filter, filteri, map, mapi, bind, flatMap, choose, chooseR, head, first, tail, take, skip, reduce, reduceRight, match, isEmpty, isNonEmpty, append, prepend, groupBy, concat, concatFirst, exists, some, flatten, chunk, length, contains, uniq, uniqBy, sort, sortBy, reverse, find, findIndex, except, union, getEqualityComparer, asMutable, iter, } /* c8 ignore end */
src/Array.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Option.ts", "retrieved_chunk": " * pipe(\n * [Option.some(10), Option.some(20)],\n * Option.map2((a, b) => a + b),\n * Option.defaultValue(0)\n * ) // => 30\n */\nexport const map2 =\n <A extends NonNullish, B extends NonNullish, C extends NonNullish>(\n map: (a: A, b: B) => C\n ) =>", "score": 0.8828999996185303 }, { "filename": "src/Option.ts", "retrieved_chunk": " * none: 0,\n * })\n * ) // => 84\n */\nexport const match =\n <A extends NonNullish, R>(matcher: OptionMatcher<A, R>) =>\n (option: Option<A>) => {\n switch (option._tag) {\n case \"Some\":\n return getMatcherResult(matcher.some, option.some)", "score": 0.8762645721435547 }, { "filename": "src/Option.ts", "retrieved_chunk": " * Option.bind(mightFailB), // Option<number>\n * Option.defaultWith(() => 0) // number\n * )\n * // => 200 if both mightFail functions return `Some`\n * // => 0 if either function returns `None`\n * ```\n */\nexport const bind = <A extends NonNullish, B extends NonNullish>(\n f: (a: A) => Option<B>\n) =>", "score": 0.8711313009262085 }, { "filename": "src/Nullable.ts", "retrieved_chunk": " * null,\n * Nullable.defaultWith(() => 42)\n * ) // => 42\n */\nexport const defaultWith =\n <A extends NonNullish>(f: () => A) =>\n (nullable: Nullable<A>): NonNullable<A> =>\n nullable != null ? nullable : f()\n/**\n * Similar to `Option.map`. Uses the given function to map the nullable value", "score": 0.8692644834518433 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n */\nexport const refine = <A extends NonNullish, B extends A>(f: Refinement<A, B>) =>\n match<A, Option<B>>({\n some: a => (f(a) ? some(a) : none),\n none: none,\n })\n/**\n * Returns the wrapped value if the `Option` is `Some`,\n * otherwise uses the given value as a default value.", "score": 0.86717689037323 } ]
typescript
if (Option.isSome(maybeB)) {
/** * An `AsyncResult` represents an asynchronous computation that may either * succeed or fail (but should never throw). It is identical to `Async<Result<A, E>`. * This module simply provides convenience functions for working with that * type because they are so frequently used in real-world programming. * * Like `Async`, `AsyncResult` represents a "cold" computation that must be * explicitly invoked/started, in contrast to `Promise`s, which are "hot." * * **Note:** You can use `Async.start` to start `AsyncResult`s because they are * just `Async`s with a constrained inner value type. * * @module AsyncResult */ import { Result } from "./Result" import { Async } from "./Async" import { pipe } from "./Composition" /** * @typeParam A The type of the `Ok` branch. * @typeParam E The type of the `Err` branch. */ export interface AsyncResult<A, E> { (): Promise<Result<A, E>> } /** * Construct a new `Ok` instance. * * @group Constructors * * @returns A new `AsyncResult` containing the given ok value. */ export const ok = <A, E = never>(ok: A): AsyncResult<A, E> => () => Promise.resolve(Result.ok(ok)) /** * Construct a new `Err` instance. * * @group Constructors * * @returns A new `AsyncResult` using the given err value. */ export const err = <E, A = never>(err: E): AsyncResult<A, E> => () => Promise.resolve(Result.err(err)) /** * Maps the wrapped `Ok` value using the given function and * returns a new `AsyncResult`. Passes `Err` values through as-is. * * @group Mapping * * @example * await pipe( * AsyncResult.ok(10), * AsyncResult.map(n => n * 2), * Async.start * ) // => Result.ok(20) */ export const map = <A, B>(f: (a: A) => B) => <E>(async: AsyncResult<A, E>): AsyncResult<B, E> => () => async().then(Result.map(f)) /** * Maps the wrapped `Err` value using the given function and * returns a new `AsyncResult`. Passes `Ok` values through as-is. * * @group Mapping * * @example * await pipe( * AsyncResult.err("err"), * AsyncResult.mapErr(s => s.length), * Async.start * ) // => Result.err(3) */ export const mapErr = <Ea, Eb>(f: (a: Ea) => Eb) => <A>(async: AsyncResult<A, Ea>): AsyncResult<A, Eb> => () => async().then(Result.mapErr(f)) /** * Takes two functions: one to map an `Ok`, one to map an `Err`. * Returns a new AsyncResult with the projected value based * on which function was used. Equivalent to calling {@link map} = * followed by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, A2, E1, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => (async: AsyncResult<A1, E1>) => () => async().then(Result.mapBoth(mapOk, mapErr)) /** * Maps the wrapped `Ok` value using a given function that * also returns an AsyncResult, and flattens the result. * Also commonly known as `flatpMap`. * * @group Mapping * * @example * declare const getNumberOfLines: (fileName: string) => AsyncResult<number, Error> * declare const sendToServer: (numLines: number) => AsyncResult<{}, Error> * * await pipe( * "log.txt", // string * getNumberOfLines, // AsyncResult<number, Error> * AsyncResult.bind(sendToServer), // AsyncResult<{}, Error> * Async.start // Promise<Result<{}, Error>> * ) * // returns Result.ok({}) if everything succeeds * // otherwise returns Result.err(Error) if something * // fell down along the way */ export const bind = <A, B, E>(f: (a: A) => AsyncResult<B, E>) => (async: AsyncResult<A, E>): AsyncResult<B, E> => async () => { const result = await async() return await pipe( result, Result.match({ ok: f, err: e => err(e), }),
Async.start ) }
/** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * Projects the wrapped `Ok` value using a given _synchronous_ function * that returns a `Result` and flattens that result into a new `AsyncResult`. * Primarily useful for composing together asynchronous workflows with * synchronous functions that may also fail. (e.g., parsing a JSON string) * * @group Mapping * * @example * declare const networkRequest: (url: string) => AsyncResult<JsonValue, Error>; * declare const parseJson: (j: JsonValue) => Result<MyType, string>; * * await pipe( * url, // string * networkRequest, // AsyncResult<JsonValue, Error> * AsyncResult.bindResult(flow( * parseJson, // Result<MyType, string> * Result.mapErr(s => new Error(s)) // Result<MyType, Error> * )), // AsyncResult<MyType, Error> * Async.start // Promise<Result<MyType, Error>> * ) * // returns Result.ok(MyType) instance if everything succeeds, * // otherwise returns Result.err(Error)F if something fell over */ export const bindResult = <A, B, E>(f: (a: A) => Result<B, E>) => (async: AsyncResult<A, E>): AsyncResult<B, E> => () => async().then(Result.bind(f)) /** * Alias for {@link bindResult}. * * @group Mapping */ export const flatMapResult = bindResult /** * Use this function to "lift" a `Result` value into the `AsyncResult` type. * Essentially, this just wraps a `Result` into a lambda that returns an * immediately-resolved `Promise` containing the `Result`. * * @group Utils * @group Constructors */ export const ofResult = <A, E>(result: Result<A, E>): AsyncResult<A, E> => () => Promise.resolve(result) /** * Use this function to "lift" an `Async` computation into an `AsyncResult`. * Essentially, this just wraps the `Async`'s inner value into a `Result.ok`. * * @group Utils * @group Constructors */ export const ofAsync = <A, E = unknown>(async: Async<A>): AsyncResult<A, E> => () => async().then(a => Result.ok(a)) /* eslint-disable func-style */ /** * Converts an `Async` computation that might reject into an * Async computation that never rejects and returns a `Result`. * (Remember that an `Async` is just a lambda returning a `Promise`.) * * If the `onThrow` callback function is given, it will be used to * convert the thrown object into the Err branch. By default, the thrown * object will be `string`-ed and wrapped in an Error if it is not an Error already. * * @group Utils * * @example * ``` * declare const doHttpThing: (url: string) => Promise<number>; * * await pipe( * AsyncResult.tryCatch(() => doHttpThing("/cats")), // AsyncResult<number, Error> * AsyncResult.mapErr(e => e.message), // AsyncResult<number, string> * Async.start // Promise<Result<number, string>> * ) * // yields `Result.ok(number)` if the call succeeded * // otherwise yields `Result.err(string)` * ``` */ export function tryCatch<A>(mightThrow: Async<A>): AsyncResult<A, Error> export function tryCatch<A, E = unknown>( mightThrow: Async<A>, onThrow: (thrown: unknown) => E ): AsyncResult<A, E> export function tryCatch<A, E = unknown>( mightThrow: Async<A>, onThrow?: (err: unknown) => E ): AsyncResult<A, unknown> { return async () => { const toError = (err: unknown) => err instanceof Error ? err : Error(String(err)) try { return Result.ok(await mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } } /* eslint-enable func-style */ /** * @ignore */ interface AsyncResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } /** * Exhaustive pattern match against an `AsyncResult`. Pass a matcher * object with cases for `ok` and `err` using either raw values or * lambdas accepting the data associated with each case. * * This pattern match unwraps the inner `Result` and returns an `Async` * computation containing the result of the match. Use {@link start} to * convert the `Async` into a `Promise` which can be `await`-ed. * * @group Pattern Matching * * @example * await pipe( * AsyncResult.ok("alright!"), * AsyncResult.match({ * ok: String.capitalize, * err: "bah, humbug!", * }), * Async.start * ) // => "Alright!" */ export const match = <A, E, R>(matcher: AsyncResultMatcher<A, E, R>) => (async: AsyncResult<A, E>): Async<R> => () => async().then(Result.match(matcher)) /** * Equivalent to both Async.start or simply invoking * the AsyncResult as a function. Aliased here for convenience. * * @group Utils */ export const start = <A, E>(async: AsyncResult<A, E>) => async() /** * Execute an arbitrary side-effect on the inner `Ok` value of an `AsyncResult` * within a pipeline of functions. Useful for logging and debugging. Passes * the inner value through unchanged. Sometimes referred to as `do` or `tap`. * * The side-effect will be invoked once the underlying `Promise` has resolved. * * @param f The side-effect to execute. Should not mutate its arguments. * @returns The `AsyncResult`, unchanged. * * @group Utils */ export const tee = <A>(f: (a: A) => void) => <E>(async: AsyncResult<A, E>): AsyncResult<A, E> => Async.tee<Result<A, E>>(Result.tee(f))(async) /** * Execute an arbitrary side-effect on the inner `Err` value of an `AsyncResult` * within a pipeline of functions. Useful for logging and debugging. Passes * the inner value through unchanged. Sometimes referred to as `do` or `tap`. * * The side-effect will be invoked once the underlying `Promise` has resolved. * * @param f The side-effect to execute. Should not mutate its arguments. * @returns The `AsyncResult`, unchanged. * * @group Utils */ export const teeErr = <E>(f: (a: E) => void) => <A>(async: AsyncResult<A, E>): AsyncResult<A, E> => Async.tee<Result<A, E>>(Result.teeErr(f))(async) /* c8 ignore start */ /** @ignore */ export const AsyncResult = { ok, err, map, mapErr, mapBoth, bind, flatMap, bindResult, flatMapResult, ofResult, ofAsync, tryCatch, match, start, tee, teeErr, } /* c8 ignore end */
src/AsyncResult.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Result.ts", "retrieved_chunk": " <E>(result: Result<A, E>) =>\n pipe(\n result,\n match({\n ok: a => a,\n err: a,\n })\n )\n/**\n * Return the inner `Ok` value or use the given lambda", "score": 0.9169619083404541 }, { "filename": "src/Result.ts", "retrieved_chunk": " <E>(result: Result<A, E>): Result<B, E> =>\n pipe(\n result,\n match({\n ok: a => ok(f(a)),\n err: e => err(e),\n })\n )\n/**\n * Map the inner `Err` value using the given function and", "score": 0.9012207984924316 }, { "filename": "src/Result.ts", "retrieved_chunk": " match({\n ok: a => {\n f(a)\n return ok(a)\n },\n err: e => err(e),\n })\n )\n/**\n * Allows some arbitrary side-effect function to be called", "score": 0.8873613476753235 }, { "filename": "src/Result.ts", "retrieved_chunk": " result,\n match({\n ok: a => ok(a),\n err: e => {\n f(e)\n return err(e)\n },\n })\n )\n/**", "score": 0.876105546951294 }, { "filename": "src/Result.ts", "retrieved_chunk": " result,\n match({\n ok: a => (refinement(a) ? ok(a) : err(onFail(a))),\n err: e => err(e),\n })\n )\n/**\n * Map the inner `Ok` value using the given function and\n * return a new `Result`. Passes `Err` values through as-is.\n *", "score": 0.8758954405784607 } ]
typescript
Async.start ) }
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2
].ok)) } else if (isErr(results[0])) {
return err(results[0].err) } else if (isErr(results[1])) { return err(results[1].err) } else { return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => { if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Array.ts", "retrieved_chunk": " */\nexport const chooseR =\n <A, E, B>(f: (a: A) => Result<B, E>) =>\n (as: readonly A[]): readonly B[] => {\n const bs: B[] = []\n for (let i = 0; i < as.length; i++) {\n const result = f(as[i])\n if (Result.isOk(result)) {\n bs.push(result.ok)\n }", "score": 0.8387488126754761 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": "export const mapBoth =\n <A1, A2, E1, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) =>\n (async: AsyncResult<A1, E1>) =>\n () =>\n async().then(Result.mapBoth(mapOk, mapErr))\n/**\n * Maps the wrapped `Ok` value using a given function that\n * also returns an AsyncResult, and flattens the result.\n * Also commonly known as `flatpMap`.\n *", "score": 0.8326115012168884 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": " * Async.start // Promise<Result<{}, Error>>\n * )\n * // returns Result.ok({}) if everything succeeds\n * // otherwise returns Result.err(Error) if something\n * // fell down along the way\n */\nexport const bind =\n <A, B, E>(f: (a: A) => AsyncResult<B, E>) =>\n (async: AsyncResult<A, E>): AsyncResult<B, E> =>\n async () => {", "score": 0.8185913562774658 }, { "filename": "src/Option.ts", "retrieved_chunk": " <\n A extends NonNullish,\n B extends NonNullish,\n C extends NonNullish,\n D extends NonNullish\n >(\n map: (a: A, b: B, c: C) => D\n ) =>\n (options: readonly [Option<A>, Option<B>, Option<C>]): Option<D> => {\n if (isSome(options[0]) && isSome(options[1]) && isSome(options[2])) {", "score": 0.8146036863327026 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": " */\nexport const ok =\n <A, E = never>(ok: A): AsyncResult<A, E> =>\n () =>\n Promise.resolve(Result.ok(ok))\n/**\n * Construct a new `Err` instance.\n *\n * @group Constructors\n *", "score": 0.814242959022522 } ]
typescript
].ok)) } else if (isErr(results[0])) {
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else if (isErr(results[1])) { return err(results[1].err) } else { return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> =>
EqualityComparer.ofEquals((r1, r2) => {
if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/NonEmptyArray.ts", "retrieved_chunk": " * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison.\n *\n * @returns A new `EqualityComparer` instance\n */\nexport const getEqualityComparer = <A>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<NonEmptyArray<A>> =>\n EqualityComparer.ofEquals((arr1, arr2) => {", "score": 0.9356896877288818 }, { "filename": "src/Nullable.ts", "retrieved_chunk": " * equals(4, 4) // => true\n * equals(4, 5) // => false\n * ```\n */\nexport const getEqualityComparer = <A extends NonNullish>(\n equalityComparer: EqualityComparer<A>\n) =>\n EqualityComparer.ofEquals<Nullable<A>>(\n (a1, a2) =>\n (a1 == null && a2 == null) ||", "score": 0.8845162987709045 }, { "filename": "src/OrderingComparer.ts", "retrieved_chunk": " * that is compatible with `Ord` from `fp-ts`.\n *\n * @returns A new instance that implements both `EqualityComparer` and `OrderingComparer`\n *\n * @group Utils\n */\nexport const deriveEqualityComparer = <A>(\n orderingComparer: OrderingComparer<A>\n): OrderingComparer<A> & EqualityComparer<A> => ({\n compare: orderingComparer.compare,", "score": 0.8749380111694336 }, { "filename": "src/EqualityComparer.ts", "retrieved_chunk": " }\n return true\n })\n/**\n * The default `EqualityComparer`, which uses reference (triple equals) equality.\n *\n * @group Primitives\n */\nexport const Default: EqualityComparer<never> = Object.freeze(\n ofEquals((a1, a2) => a1 === a2)", "score": 0.8678579330444336 }, { "filename": "src/NonEmptyArray.ts", "retrieved_chunk": " */\nexport const sort =\n <A>(orderingComparer: OrderingComparer<A> = OrderingComparer.Default) =>\n (as: NonEmptyArray<A>): NonEmptyArray<A> =>\n as.slice(0).sort(orderingComparer.compare) as unknown as NonEmptyArray<A>\n/**\n * Get an `EqualityComparer` that represents structural equality for a non-empty array\n * of type `A` by giving this function an `EqualityComparer` for each `A` element.\n *\n * @group Equality", "score": 0.8665431141853333 } ]
typescript
EqualityComparer.ofEquals((r1, r2) => {
/** * An `AsyncResult` represents an asynchronous computation that may either * succeed or fail (but should never throw). It is identical to `Async<Result<A, E>`. * This module simply provides convenience functions for working with that * type because they are so frequently used in real-world programming. * * Like `Async`, `AsyncResult` represents a "cold" computation that must be * explicitly invoked/started, in contrast to `Promise`s, which are "hot." * * **Note:** You can use `Async.start` to start `AsyncResult`s because they are * just `Async`s with a constrained inner value type. * * @module AsyncResult */ import { Result } from "./Result" import { Async } from "./Async" import { pipe } from "./Composition" /** * @typeParam A The type of the `Ok` branch. * @typeParam E The type of the `Err` branch. */ export interface AsyncResult<A, E> { (): Promise<Result<A, E>> } /** * Construct a new `Ok` instance. * * @group Constructors * * @returns A new `AsyncResult` containing the given ok value. */ export const ok = <A, E = never>(ok: A): AsyncResult<A, E> => () => Promise.resolve(Result.ok(ok)) /** * Construct a new `Err` instance. * * @group Constructors * * @returns A new `AsyncResult` using the given err value. */ export const err = <E, A = never>(err: E): AsyncResult<A, E> => () => Promise.resolve(Result.err(err)) /** * Maps the wrapped `Ok` value using the given function and * returns a new `AsyncResult`. Passes `Err` values through as-is. * * @group Mapping * * @example * await pipe( * AsyncResult.ok(10), * AsyncResult.map(n => n * 2), * Async.start * ) // => Result.ok(20) */ export const map = <A, B>(f: (a: A) => B) => <E>(async: AsyncResult<A, E>): AsyncResult<B, E> => () => async().then(Result.map(f)) /** * Maps the wrapped `Err` value using the given function and * returns a new `AsyncResult`. Passes `Ok` values through as-is. * * @group Mapping * * @example * await pipe( * AsyncResult.err("err"), * AsyncResult.mapErr(s => s.length), * Async.start * ) // => Result.err(3) */ export const mapErr = <Ea, Eb>(f: (a: Ea) => Eb) => <A>(async: AsyncResult<A, Ea>): AsyncResult<A, Eb> => () => async().then(Result.mapErr(f)) /** * Takes two functions: one to map an `Ok`, one to map an `Err`. * Returns a new AsyncResult with the projected value based * on which function was used. Equivalent to calling {@link map} = * followed by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, A2, E1, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => (async: AsyncResult<A1, E1>) => () => async().then(Result.mapBoth(mapOk, mapErr)) /** * Maps the wrapped `Ok` value using a given function that * also returns an AsyncResult, and flattens the result. * Also commonly known as `flatpMap`. * * @group Mapping * * @example * declare const getNumberOfLines: (fileName: string) => AsyncResult<number, Error> * declare const sendToServer: (numLines: number) => AsyncResult<{}, Error> * * await pipe( * "log.txt", // string * getNumberOfLines, // AsyncResult<number, Error> * AsyncResult.bind(sendToServer), // AsyncResult<{}, Error> * Async.start // Promise<Result<{}, Error>> * ) * // returns Result.ok({}) if everything succeeds * // otherwise returns Result.err(Error) if something * // fell down along the way */ export const bind = <A, B, E>(f: (a: A) => AsyncResult<B, E>) => (async: AsyncResult<A, E>): AsyncResult<B, E> => async () => { const result = await async() return await pipe( result, Result.match({ ok: f, err: e => err(e), }), Async.start ) } /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * Projects the wrapped `Ok` value using a given _synchronous_ function * that returns a `Result` and flattens that result into a new `AsyncResult`. * Primarily useful for composing together asynchronous workflows with * synchronous functions that may also fail. (e.g., parsing a JSON string) * * @group Mapping * * @example * declare const networkRequest: (url: string) => AsyncResult<JsonValue, Error>; * declare const parseJson: (j: JsonValue) => Result<MyType, string>; * * await pipe( * url, // string * networkRequest, // AsyncResult<JsonValue, Error> * AsyncResult.bindResult(flow( * parseJson, // Result<MyType, string> * Result.mapErr(s => new Error(s)) // Result<MyType, Error> * )), // AsyncResult<MyType, Error> * Async.start // Promise<Result<MyType, Error>> * ) * // returns Result.ok(MyType) instance if everything succeeds, * // otherwise returns Result.err(Error)F if something fell over */ export const bindResult = <A, B, E>(f: (a: A) => Result<B, E>) => (async: AsyncResult<A, E>): AsyncResult<B, E> => () => async().then(Result.bind(f)) /** * Alias for {@link bindResult}. * * @group Mapping */ export const flatMapResult = bindResult /** * Use this function to "lift" a `Result` value into the `AsyncResult` type. * Essentially, this just wraps a `Result` into a lambda that returns an * immediately-resolved `Promise` containing the `Result`. * * @group Utils * @group Constructors */ export const ofResult = <A, E>(result: Result<A, E>): AsyncResult<A, E> => () => Promise.resolve(result) /** * Use this function to "lift" an `Async` computation into an `AsyncResult`. * Essentially, this just wraps the `Async`'s inner value into a `Result.ok`. * * @group Utils * @group Constructors */ export const ofAsync = <A, E = unknown>(async: Async<A>): AsyncResult<A, E> => () => async().then(a => Result.ok(a)) /* eslint-disable func-style */ /** * Converts an `Async` computation that might reject into an * Async computation that never rejects and returns a `Result`. * (Remember that an `Async` is just a lambda returning a `Promise`.) * * If the `onThrow` callback function is given, it will be used to * convert the thrown object into the Err branch. By default, the thrown * object will be `string`-ed and wrapped in an Error if it is not an Error already. * * @group Utils * * @example * ``` * declare const doHttpThing: (url: string) => Promise<number>; * * await pipe( * AsyncResult.tryCatch(() => doHttpThing("/cats")), // AsyncResult<number, Error> * AsyncResult.mapErr(e => e.message), // AsyncResult<number, string> * Async.start // Promise<Result<number, string>> * ) * // yields `Result.ok(number)` if the call succeeded * // otherwise yields `Result.err(string)` * ``` */ export function tryCatch<A>(mightThrow: Async<A>): AsyncResult<A, Error> export function tryCatch<A, E = unknown>( mightThrow: Async<A>, onThrow: (thrown: unknown) => E ): AsyncResult<A, E> export function tryCatch<A, E = unknown>( mightThrow: Async<A>, onThrow?: (err: unknown) => E ): AsyncResult<A, unknown> { return async () => { const toError = (err: unknown) => err instanceof Error ? err : Error(String(err)) try { return Result.ok(await mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } } /* eslint-enable func-style */ /** * @ignore */ interface AsyncResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } /** * Exhaustive pattern match against an `AsyncResult`. Pass a matcher * object with cases for `ok` and `err` using either raw values or * lambdas accepting the data associated with each case. * * This pattern match unwraps the inner `Result` and returns an `Async` * computation containing the result of the match. Use {@link start} to * convert the `Async` into a `Promise` which can be `await`-ed. * * @group Pattern Matching * * @example * await pipe( * AsyncResult.ok("alright!"), * AsyncResult.match({ * ok: String.capitalize, * err: "bah, humbug!", * }), * Async.start * ) // => "Alright!" */ export const match = <A, E, R>(matcher: AsyncResultMatcher<A, E, R>) => (async: AsyncResult<A, E>): Async<R> => () => async().then(Result.match(matcher)) /** * Equivalent to both Async.start or simply invoking * the AsyncResult as a function. Aliased here for convenience. * * @group Utils */ export const start = <A, E>(async: AsyncResult<A, E>) => async() /** * Execute an arbitrary side-effect on the inner `Ok` value of an `AsyncResult` * within a pipeline of functions. Useful for logging and debugging. Passes * the inner value through unchanged. Sometimes referred to as `do` or `tap`. * * The side-effect will be invoked once the underlying `Promise` has resolved. * * @param f The side-effect to execute. Should not mutate its arguments. * @returns The `AsyncResult`, unchanged. * * @group Utils */ export const tee = <A>(f: (a: A) => void) => <E>(async: AsyncResult<A, E>): AsyncResult<A, E> => Async.tee<Result<A, E>>(Result.tee(f))(async) /** * Execute an arbitrary side-effect on the inner `Err` value of an `AsyncResult` * within a pipeline of functions. Useful for logging and debugging. Passes * the inner value through unchanged. Sometimes referred to as `do` or `tap`. * * The side-effect will be invoked once the underlying `Promise` has resolved. * * @param f The side-effect to execute. Should not mutate its arguments. * @returns The `AsyncResult`, unchanged. * * @group Utils */ export const teeErr = <E>(f: (a: E) => void) => <A>(async: AsyncResult<A, E>): AsyncResult<A, E> =>
Async.tee<Result<A, E>>(Result.teeErr(f))(async) /* c8 ignore start */ /** @ignore */ export const AsyncResult = {
ok, err, map, mapErr, mapBoth, bind, flatMap, bindResult, flatMapResult, ofResult, ofAsync, tryCatch, match, start, tee, teeErr, } /* c8 ignore end */
src/AsyncResult.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Async.ts", "retrieved_chunk": " * ```\n */\nexport const tee =\n <A>(f: (a: A) => void) =>\n (async: Async<A>): Async<A> =>\n async () => {\n const a = await async()\n f(a)\n return a\n }", "score": 0.8898414373397827 }, { "filename": "src/Result.ts", "retrieved_chunk": " * Result.map(n => n + 1), // inner value is unchanged\n * Result.defaultValue(0)\n * ) // => 24\n * ```\n */\nexport const tee =\n <A>(f: (a: A) => void) =>\n <E>(result: Result<A, E>): Result<A, E> =>\n pipe(\n result,", "score": 0.8755480647087097 }, { "filename": "src/Async.ts", "retrieved_chunk": " */\nexport const bind =\n <A, B>(f: (a: A) => Async<B>) =>\n (async: Async<A>): Async<B> =>\n () =>\n async().then(a => f(a)())\n/**\n * Alias of {@link bind}.\n *\n * @group Mapping", "score": 0.8726974725723267 }, { "filename": "src/Async.ts", "retrieved_chunk": " *\n * @group Utils\n */\nexport const asyncify =\n <F extends (...args: any[]) => Promise<any>>(\n f: F\n ): ((...args: Parameters<F>) => Async<Awaited<ReturnType<F>>>) =>\n (...args: Parameters<F>) =>\n () =>\n f(...args)", "score": 0.8679184913635254 }, { "filename": "src/Result.ts", "retrieved_chunk": " * Result.err(\"melted\"),\n * Result.teeErr(console.log), // logs `melted`\n * Result.mapErr(s => s.length), // inner value is unchanged\n * ) // => Result.err(6)\n * ```\n */\nexport const teeErr =\n <E>(f: (e: E) => void) =>\n <A>(result: Result<A, E>): Result<A, E> =>\n pipe(", "score": 0.8615459203720093 } ]
typescript
Async.tee<Result<A, E>>(Result.teeErr(f))(async) /* c8 ignore start */ /** @ignore */ export const AsyncResult = {
/** * A suite of useful functions for working with readonly arrays. These functions * provide a curried API that works seamlessly with right-to-left function * composition and preserve the `readonly` type. * * @module Array */ import { Predicate, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { Result } from "./Result" import { pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" import { OrderingComparer } from "./OrderingComparer" import { NonEmptyArray } from "./NonEmptyArray" /* eslint-disable func-style */ /** * Curried and readonly version of the built-in `filter`. * Accepts a plain predicate function or a refinement * function (a.k.a. type guard). * * @group Filtering */ export function filter<A, B extends A>( refinement: Refinement<A, B> ): (as: readonly A[]) => readonly B[] export function filter<A>( predicate: Predicate<A> ): <B extends A>(bs: readonly B[]) => readonly B[] export function filter<A>(predicate: Predicate<A>): (as: readonly A[]) => readonly A[] export function filter<A>(f: Predicate<A>) { return <B extends A>(as: readonly B[]) => as.filter(f) } /* eslint-enable func-style */ /** * Like {@link filter}, but the predicate function also accepts the * index of the element as an argument. * * @group Filtering */ export const filteri = <A>(f: (a: A, i: number) => boolean) => (as: readonly A[]): readonly A[] => as.filter(f) /** * Curried and readonly version of the built-in `map`. * * @group Mapping */ export const map = <A, B>(f: (a: A) => B) => (as: readonly A[]): readonly B[] => as.map(f) /** * Like {@link map} but the map function also accepts the * index of the element as an argument. * * @group Mapping */ export const mapi = <A, B>(f: (a: A, i: number) => B) => (as: readonly A[]): readonly B[] => as.map(f) /** * Maps each value of the array into an `Option`, and keeps only the inner * values of those `Option`s that are`Some`. Essentially, this is a combined map + * filter operation where each element of the array is mapped into an `Option` * and an `isSome` check is used as the filter function. * * @group Mapping * * @example * pipe( * [32, null, 55, undefined, 89], // (number | null | undefined)[] * Array.choose(x => pipe( * x, // number | null | undefined * Option.ofNullish, // Option<number> * Option.map(String) // Option<string> * )) // string[] * ) // => ["32", "55", "89"] */ export const choose = <A, B extends NonNullish>(f: (a: A) => Option<B>) => (as: readonly A[]): readonly B[] => { const bs: B[] = [] for (let i = 0; i < as.length; i++) { const maybeB = f(as[i]) if (Option.isSome(maybeB)) { bs.push(maybeB.some) } } return bs } /** * Like {@link choose}, but maps each value of the array into a `Result`, * and keeps only the values where the projection returns `Ok`. Essentially, * this is a combined map + filter operation where each element of the array * is mapped into an `Result` and an `isOk` check is used as the filter function. * * @group Mapping * * @example * pipe( * [32, null, 55, undefined, 89], // (number | null | undefined)[] * Array.chooseR(x => pipe( * x, // number | null | undefined * Option.ofNullish, // Option<number> * Option.map(String), // Option<string> * Result.ofOption(() => "err") // Result<string, string> * )) // string[] * ) // => ["32", "55", "89"] */ export const chooseR = <A, E, B>(f: (a: A) => Result<B, E>) => (as: readonly A[]): readonly B[] => { const bs: B[] = [] for (let i = 0; i < as.length; i++) { const result = f(as[i])
if (Result.isOk(result)) {
bs.push(result.ok) } } return bs } /** * Get the first element of the array (wrapped in `Some`) if * non-empty, otherwise `None`. * * @group Utils * @group Pattern Matching * * @example * ```ts * Array.head([]) // => `Option.none` * Array.head([1, 2, 3]) // => `Option.some(1)` * ``` */ export const head = <A extends NonNullish>(as: readonly A[]): Option<A> => as.length > 0 ? Option.some(as[0]) : Option.none /** * Alias of {@link head}. * * @group Utils * @group Pattern Matching */ export const first = head /** * Get a new array containing all values except the first * one (wrapped in `Some`) if non-empty, otherwise `None`. * * @group Utils * @group Pattern Matching * * @example * pipe( * [1, 2, 3, 4], * Array.tail * ) // => Option.some([2, 3, 4]) */ export const tail = <A>(as: readonly A[]): Option<readonly A[]> => { if (as.length === 0) { return Option.none } // eslint-disable-next-line @typescript-eslint/no-unused-vars const [_, ...tail] = as return Option.some(tail) } /** * Get the first `n` elements of the array. Will return the entire * array if `n` is greater than the length of the array. * * @param count is normalized to a non-negative integer * * @group Utils * * @example * pipe( * [1, 2, 3, 4, 5, 6], * Array.take(3) * ) // => [1, 2, 3] */ export const take = (count: number) => <A>(as: readonly A[]): readonly A[] => { const c = count <= 0 ? 0 : Math.floor(count) if (c > as.length) { return as } const out: A[] = [] for (let i = 0; i < as.length && i < c; i++) { out.push(as[i]) } return out } /** * Get the remaining elements of the array * after skipping `n` elements. Returns empty if the * skip count goes past the end of the array. * * @group Utils * * @param count is normalized to a non-negative integer * * @example * pipe( * [1, 2, 3, 4, 5, 6], * Array.skip(3) * ) // => [4, 5, 6] */ export const skip = (count: number) => <A>(as: readonly A[]): readonly A[] => { const c = count <= 0 ? 0 : Math.floor(count) if (c >= as.length) { return [] } const out: A[] = [] for (let i = c; i < as.length; i++) { out.push(as[i]) } return out } /** * Curried and readonly version of the built-in `Array.prototype.reduce`. Takes * the initial value first instead of last. * * @group Utils * @group Folding */ export const reduce = <A, B>(initialValue: B, reducer: (acc: B, next: A) => B) => (as: readonly A[]): B => as.reduce(reducer, initialValue) /** * Curried and readonly version of the built-in `Array.prototype.reduceRight`. * Takes the initial value first instead of last. * * @group Utils * @group Folding */ export const reduceRight = <A, B>(initialValue: B, reducer: (acc: B, next: A) => B) => (as: readonly A[]): B => as.reduceRight(reducer, initialValue) const isRawValue = <A, R>(caseFn: R | ((ok: A) => R)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * @ignore */ interface ArrayMatcher<A, R> { empty: (() => R) | R nonEmpty: ((as: NonEmptyArray<A>) => R) | R } /** * Exhaustive pattern match against an array to "unwrap" its values. Provide * a matcher object to handle both the `empty` and `nonEmpty` cases. * The matcher can use lambdas or raw values. In the `nonEmpty` case, * the lambda will be given a `NonEmptyArray`. * * @group Pattern Matching * * @example * ```ts * pipe( * ["a", "b"], * Array.match({ * empty: () => "default", * nonEmpty: Array.reduceRight("", (a, b) => `${a}${b}`) * }) * ) // => "ba" * ``` */ export const match = <A, R>(matcher: ArrayMatcher<A, R>) => (as: readonly A[]): R => as.length > 0 ? getMatcherResult(matcher.nonEmpty, as as NonEmptyArray<A>) : getMatcherResult(matcher.empty, undefined) /** * Type guard that tests whether the given array is equivalent * to the empty tuple type. * * @group Type Guards * @group Utils */ export const isEmpty = <A>(as: readonly A[]): as is readonly [] => as.length === 0 /** * Type guard that tests whether the given array is a `NonEmptyArray` * * @group Type Guards * @group Utils */ export const isNonEmpty = <A>(as: readonly A[]): as is NonEmptyArray<A> => as.length > 0 /** * Also commonly known as `flatMap`. Maps each element of the array * given a function that itself returns an array, then flattens the result. * * @group Mapping * * @example * pipe( * [1, 2, 3], * Array.bind(n => [n, n]) * ) // => [1, 1, 2, 2, 3, 3] */ export const bind = <A, B>(f: (a: A) => readonly B[]) => (as: readonly A[]): readonly B[] => as.flatMap(f) /** * Alias of {@link bind}. * * @group Mapping */ export const flatMap = bind /** * Add an element to the _end_ of an array. Always returns * a `NonEmptyArray`. * * @group Utils */ export const append = <A>(a: A) => (as: readonly A[]): NonEmptyArray<A> => [...as, a] as unknown as NonEmptyArray<A> /** * Also known as `cons`. Insert an element at the beginning * of an array. Always returns a `NonEmptyArray`. * * @group Utils * * @example * pipe( * [2, 3], * Array.prepend(1) * ) // => [1, 2, 3] */ export const prepend = <A>(a: A) => (as: readonly A[]): NonEmptyArray<A> => [a, ...as] /** * Return a Map of keys to groups, where the selector function * is used to generate a string key that determines in which group * each array element is placed. * * @group Grouping * @group Utils * * @example * pipe( * [1, 2, 1, 2, 3, 3, 5], * Array.groupBy(String) * ) * // structurally equivalent to * new Map([ * ['1', [1, 1]], * ['2', [2, 2]], * ['3', [3, 3]], * ['5', [5]] * ]) */ export const groupBy = <A>(selector: (a: A) => string) => (as: readonly A[]): ReadonlyMap<string, NonEmptyArray<A>> => { const groups: Map<string, NonEmptyArray<A>> = new Map() as.forEach(a => { const key = selector(a) return groups.has(key) ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion groups.set(key, pipe(groups.get(key)!, append(a))) : groups.set(key, [a]) }) return groups } /** * Add an array of values to the _end_ of the subsequently * passed (partially applied) array, in a way that makes sense * when reading top-to-bottom/left-to-right using `pipe`. * * @group Utils * * @example * pipe( * [1, 2], * Array.concat([3, 4]) * ) // => [1, 2, 3, 4] */ export const concat = <A>(addToEnd: readonly A[]) => (as: readonly A[]): readonly A[] => [...as, ...addToEnd] /** * Like {@link concat}, except this adds an array of values to the * _beginning_ of the subsequently (partially applied) array, * in a way that makes more sense when _not_ using `pipe`. * * @group Utils * * @example * ```ts * // Reads "backwards" when used with `pipe` * pipe( * ["a", "b"], * Array.concatFirst(["c", "d"]) * ) // => ["c", "d", "a", "b"] * // Reads better when *not* used with `pipe` * Array.concatFirst(["a", "b"])(["c", "d"]) // => ["a", "b", "c", "d"] * ``` */ export const concatFirst = <A>(addToFront: readonly A[]) => (as: readonly A[]): readonly A[] => [...addToFront, ...as] /** * Returns true if at least one element of the array * satisfies the given predicate. Curried version of * `Array.prototype.some`. * * @group Utils */ export const exists = <A>(predicate: (a: A) => boolean) => (as: readonly A[]): boolean => as.some(predicate) /** * Alias of {@link exists}. * * @group Utils */ export const some = exists /** * Equivalent to calling `Array.prototype.flat()` with a depth of 1. * * @group Utils */ export const flatten = <A>(as: readonly (readonly A[])[]): readonly A[] => as.flat() /** * Split an array into chunks of a specified size. The final * chunk will contain fewer elements than the specified size if * the array is not evenly divisible by the specified size. * * @remarks * **Note:** Will return `[]`, _not_ `[[]]` if given an empty array. * * @param maxChunkSize Normalized to a positive integer. * * @example * pipe( * ["a", "b", "c", "d", "e"], * Array.chunk(2) * ) // => [["a", "b"], ["c", "d"], ["e"]] * * @group Utils * @group Grouping */ export const chunk = (maxChunkSize: number) => <A>(as: readonly A[]): readonly NonEmptyArray<A>[] => { if (isEmpty(as)) { return [] } const chunkSize = maxChunkSize <= 1 ? 1 : Math.floor(maxChunkSize) const numChunks = Math.ceil(as.length / chunkSize) // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const chunks: A[][] = [...globalThis.Array(numChunks)].map(() => []) let chunkIndex = 0 for (let i = 0; i < as.length; i++) { if (i !== 0 && i % chunkSize === 0) { chunkIndex++ } chunks[chunkIndex].push(as[i]) } return chunks as unknown as readonly NonEmptyArray<A>[] } /** * Get the length of an array. * * @group Utils */ export const length = <A>(as: readonly A[]) => as.length /** * Returns true if the given element is in the array. * Optionally, pass an `EqualityComparer` to use. Uses * reference (triple equals) equality by default. * * @group Utils */ export const contains = <A>(a: A, equalityComparer: EqualityComparer<A> = EqualityComparer.Default) => (as: readonly A[]): boolean => { if (isEmpty(as)) { return false } const predicate = (test: A) => equalityComparer.equals(a, test) return as.some(predicate) } /** * Return a new array containing only unique values. If * passed, uses the `EqualityComparer` to test uniqueness. * Defaults to using reference equality (triple equals). * * @group Utils * * @example * pipe( * [3, 2, 1, 2, 1, 4, 9], * Array.uniq() * ) // => [3, 2, 1, 4, 9] */ export const uniq = <A>(equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } const out: A[] = [] as.forEach(a => { if (!contains(a, equalityComparer)(out)) { out.push(a) } }) return out } /** * Returns a new array containing only unique values as determined * by mapping each element with the given function and optionally * passing an equality comparer to use on the mapped elements. * Defaults to using reference equality (triple equals). * * @group Utils * * @example * pipe( * [{ name: "Rufus" }, { name: "Rex" }, { name: "Rufus" }], * Array.uniqBy(p => p.name) * ) // => [{ name: "Rufus" }, { name: "Rex" }] */ export const uniqBy = <A, B>(f: (a: A) => B, equalityComparer?: EqualityComparer<B>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } const out: A[] = [] const projections: B[] = [] as.forEach(a => { const projected = f(a) if (!contains(projected, equalityComparer)(projections)) { projections.push(projected) out.push(a) } }) return out } /** * Get a new array with elements sorted. If given, will use the * `OrderingComparer`. Otherwise, uses the default JavaScript ASCII-based sort. * * @group Utils * * @example * declare const petByNameComparer: OrderingComparer<Pet> * * const pets: readonly Pet[] = [ * { name: "Fido" }, * { name: "Albus" }, * { name: "Rex" }, * { name: "Gerald" } * ] * * pipe( * pets, * Array.sort(petByNameComparer), * Array.map(p => p.name) * ) // => [ "Albus", "Fido", "Gerald", "Rex" ] */ export const sort = <A>(orderingComparer?: OrderingComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } return as.slice(0).sort(orderingComparer?.compare) } /** * Get a new array with elements sorted based on the sort-order * of each mapped element produced by the given mapping function. * If given, will use the `OrderingComparer`. Otherwise, defaults to an * OrderingComparer that `String`s the mapped element and uses the * default ASCII-based sort. * * @group Utils */ export const sortBy = <A, B>( f: (a: A) => B, orderingComparer: OrderingComparer<B> = OrderingComparer.Default ) => (as: readonly A[]): readonly A[] => isEmpty(as) ? [] : as.slice(0).sort((o1: A, o2: A) => orderingComparer.compare(f(o1), f(o2))) /** * Get a new array with the elements in reverse order. * * @group Utils */ export const reverse = <A>(as: readonly A[]): readonly A[] => as.slice(0).reverse() /** * Get the _first_ element in the array (wrapped in a `Some`) that * returns `true` for the given predicate, or `None` if no such * element exists. * * @group Utils */ export const find = <A extends NonNullish>(predicate: Predicate<A>) => (as: readonly A[]): Option<A> => Option.ofNullish(as.find(predicate)) /** * Get the _first_ index of the array (wrapped in a `Some`) for * which the element at that index returns true for the given predicate, * or `None` if no such index/element exists. * * @group Utils */ export const findIndex = <A>(predicate: Predicate<A>) => (as: readonly A[]): Option<number> => { const result = as.findIndex(predicate) return result < 0 ? Option.none : Option.some(result) } /** * Get a new array containing only those elements that are not * in the given `excludeThese` array. If given, will use the * EqualityComparer. Otherwise, defaults to reference equality * (triple equals). * * @group Utils * * @example * pipe( * [1, 2, 3, 4, 5], * Array.except([2, 5]) * ) // => [1, 3, 4] */ export const except = <A>(excludeThese: readonly A[], equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } if (isEmpty(excludeThese)) { return as } const out: A[] = [] for (let i = 0; i < as.length; i++) { if (!pipe(excludeThese, contains(as[i], equalityComparer))) { out.push(as[i]) } } return out } /** * Get a new array containing the set union of two arrays, defined as the * set of elements contained in both arrays. **Remember:** sets only contain * unique elements. If you just need to join two arrays together, use {@link concat}. * * @group Utils */ export const union = <A>(unionWith: readonly A[], equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => isEmpty(unionWith) && isEmpty(as) ? [] : pipe(as, concat(unionWith), uniq(equalityComparer)) /** * Get an {@link EqualityComparer} that represents structural equality for an array * of type `A` by giving this function an `EqualityComparer` for each `A` element. * * @group Equality * @group Utils * * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison. * * @returns A new `EqualityComparer` instance * * @example * const eq = Array.getEqualityComparer(EqualityComparer.Number) * eq.equals([1, 2, 3], [1, 2, 3]) // => true * eq.equals([1, 3], [3, 1]) // => false */ export const getEqualityComparer = <A>({ equals, }: EqualityComparer<A>): EqualityComparer<readonly A[]> => EqualityComparer.ofEquals((arr1, arr2) => { if (isEmpty(arr1) && isEmpty(arr2)) { return true } if (arr1.length !== arr2.length) { return false } for (let i = 0; i < arr1.length; i++) { if (!equals(arr1[i], arr2[i])) { return false } } return true }) /** * Does not affect the passed array at runtime. (Effectively executes an identity * function) Removes the `readonly` part of the **type** only. * * @group Utils */ export const asMutable = <A>(as: readonly A[]) => as as A[] /** * Execute an arbitrary side effect for each element of the array. Essentially a * curried version of the built-in `forEach` method. * * @group Utils */ export const iter = <A>(f: (a: A) => void) => (as: readonly A[]): void => as.forEach(a => f(a)) /** @ignore */ export const Array = { filter, filteri, map, mapi, bind, flatMap, choose, chooseR, head, first, tail, take, skip, reduce, reduceRight, match, isEmpty, isNonEmpty, append, prepend, groupBy, concat, concatFirst, exists, some, flatten, chunk, length, contains, uniq, uniqBy, sort, sortBy, reverse, find, findIndex, except, union, getEqualityComparer, asMutable, iter, } /* c8 ignore end */
src/Array.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/AsyncResult.ts", "retrieved_chunk": " * Async.start // Promise<Result<{}, Error>>\n * )\n * // returns Result.ok({}) if everything succeeds\n * // otherwise returns Result.err(Error) if something\n * // fell down along the way\n */\nexport const bind =\n <A, B, E>(f: (a: A) => AsyncResult<B, E>) =>\n (async: AsyncResult<A, E>): AsyncResult<B, E> =>\n async () => {", "score": 0.8725736737251282 }, { "filename": "src/Result.ts", "retrieved_chunk": " * ok: a => `${a.length}`,\n * err: s => `${s}!`\n * })\n * ) // => \"failure!\"\n * ```\n */\nexport const match =\n <A, E, R>(matcher: ResultMatcher<A, E, R>) =>\n (result: Result<A, E>) => {\n switch (result._tag) {", "score": 0.8642927408218384 }, { "filename": "src/Async.ts", "retrieved_chunk": " */\nexport const sequential =\n <A>(asyncs: readonly Async<A>[]): Async<readonly A[]> =>\n async () => {\n const results: A[] = []\n for (let i = 0; i < asyncs.length; i++) {\n results.push(await asyncs[i]())\n }\n return results\n }", "score": 0.8616759777069092 }, { "filename": "src/Result.ts", "retrieved_chunk": " * Result.map(n => n + 1), // inner value is unchanged\n * Result.defaultValue(0)\n * ) // => 24\n * ```\n */\nexport const tee =\n <A>(f: (a: A) => void) =>\n <E>(result: Result<A, E>): Result<A, E> =>\n pipe(\n result,", "score": 0.8588799238204956 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": " * @example\n * await pipe(\n * AsyncResult.err(\"err\"),\n * AsyncResult.mapErr(s => s.length),\n * Async.start\n * ) // => Result.err(3)\n */\nexport const mapErr =\n <Ea, Eb>(f: (a: Ea) => Eb) =>\n <A>(async: AsyncResult<A, Ea>): AsyncResult<A, Eb> =>", "score": 0.847821831703186 } ]
typescript
if (Result.isOk(result)) {
/** * The `Deferred` type represents the state of some asynchronous operation. The * operation can either be `NotStarted`, `InProgress`, or `Resolved`. When the * operation is resolved, it has some data attached to it that represents the * outcome of the asyncrhonous work. * * This type is frequently used with `Result` as the data of the `Resolved` * branch, because it is a common situation to model the outcome of an asynchronous * operation that can fail. * * This type is especially helpful in Redux stores (or in the React `useReducer` * state) because it allows you to determinstically model the state of an async * operation as one value. I.e., instead of using separate flags that are * _implicitly_ related to each other (e.g., `notStarted`, `loading`, `result`), * you know for a fact that the async work can only be in one of three states, * and the data present on the resolved state is _only_ present on the resolved * state. * * @example * declare const def: Deferred<ApiResponse> * * pipe( * def, * Deferred.match({ * notStarted: "Not Started", * inProgress: "In Progress", * resolved: response => response.body * }) * ) * * @module Deferred */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive } from "./prelude" import { pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" /** The `NotStarted` type. */ export interface NotStarted extends Tagged<"NotStarted", object> {} /** The `InProgress` type. */ export interface InProgress extends Tagged<"InProgress", object> {} /** The `Resolved` type. */ export interface Resolved<A> extends Tagged<"Resolved", { resolved: A }> {} /** A discriminated union type representing a `Deferred` value. */ export type Deferred<A> = NotStarted | InProgress | Resolved<A> /** * The static `NotStarted` instance. * * @group Constructors */ export const notStarted: Deferred<never> = Object.freeze({ _tag: "NotStarted" }) /** * The static `InProgress` instance. * * @group Constructors */ export const inProgress: Deferred<never> = Object.freeze({ _tag: "InProgress" }) /** * Construct a new `Resolved` instance with the given data attached. * * @param a The data that will be wrapped in the `Deferred`. * * @group Constructors */ export const resolved = <A>(a: A): Deferred<A> => ({ _tag: "Resolved", resolved: a }) /** @ignore */ interface DeferredMatcher<A, R> { readonly notStarted: (() => R) | R readonly inProgress: (() => R) | R readonly resolved: ((a: A) => R) | R } /** @ignore */ interface PartialDeferredMatcher<A, R> extends Partial<DeferredMatcher<A, R>> { readonly orElse: (() => R) | R } type Func<T> = (...args: any[]) => T type FuncOrValue<T> = Func<T> | T const resultOrValue = <T>(f: FuncOrValue<T>, ...args: any[]) => { const isFunc = (f: FuncOrValue<T>): f is Func<T> => typeof f === "function" // eslint-disable-next-line @typescript-eslint/no-unsafe-argument return isFunc(f) ? f(...args) : f } /** * Exhaustively pattern match against a `Deferred` value. Provide either * a value or a lambda to use for each case. If you provide a lambda to the * `resolved` case, it will be given the data associated with the `Resolved` * instance. * * See docs for {@link Deferred} for example. * * @param matcher The matcher object to use. * * @group Pattern Matching * * @example * ``` * declare const def: Deferred<MyApiResponse> * pipe( * def, * Deferred.match({ * notStarted: "", * inProgress: "Loading...", * resolved: resp => resp?.body ?? "" * }) * ) // => the string produced in each case, depending on the value of `def` * ``` */ export const match = <A, R>(matcher: DeferredMatcher<A, R>) => (deferred: Deferred<A>) => { switch (deferred._tag) { case "NotStarted": return resultOrValue(matcher.notStarted) case "InProgress": return resultOrValue(matcher.inProgress) case "Resolved":
return resultOrValue(matcher.resolved, deferred.resolved) /* c8 ignore next 2 */ default: return assertExhaustive(deferred) as R }
} /** * Non-exhaustive pattern match against a `Deferred`. Provide a lambda or raw value * to return for the various cases. (But don't specify all the cases. You should use * {@link match} if you want exhaustive case checking.) Then also provide a raw value * or lambda to use for the `orElse` case if the check falls through all other cases. * * @group Pattern Matching * * @example * ``` * declare const def: Deferred<number> * pipe( * def, * Deferred.matchOrElse({ * resolved: statusCode => `Status: ${statusCode}`, * orElse: 'Not Finished' // effectively captures both "in progress" and "not started" cases together * }) * ) * ``` */ export const matchOrElse = <A, R>(matcher: PartialDeferredMatcher<A, R>) => (deferred: Deferred<A>) => { switch (deferred._tag) { case "NotStarted": return resultOrValue( matcher.notStarted != null ? matcher.notStarted : matcher.orElse ) case "InProgress": return resultOrValue( matcher.inProgress != null ? matcher.inProgress : matcher.orElse ) case "Resolved": return matcher.resolved != null ? resultOrValue(matcher.resolved, deferred.resolved) : resultOrValue(matcher.orElse) /* c8 ignore next 2 */ default: return resultOrValue(matcher.orElse) } } /** * Get whether the `Deferred` is either in progress or not started. * * @group Utils */ export const isUnresolved: <A>(deferred: Deferred<A>) => boolean = matchOrElse({ resolved: false, orElse: true, }) /** * Gets whether the `Deferred` is in progress. * * @group Utils */ export const isInProgress = <A>(deferred: Deferred<A>): deferred is InProgress => pipe( deferred, matchOrElse({ inProgress: true, orElse: false, }) ) /** * Gets whether the `Deferred` is resolved. * * @group Utils */ export const isResolved = <A>(deferred: Deferred<A>): deferred is Resolved<A> => pipe( deferred, matchOrElse({ resolved: true, orElse: false, }) ) /** * Gets whether the `Deferred` is resolved with data equal to a specific value. * Uses the `EqualityComparer` if given, otherwise defaults to reference (triple * equals) equality. * * @group Pattern Matching * @group Utils * * @example * pipe( * Deferred.resolved(101), * Deferred.isResolvedWith(100, EqualityComparer.Number) * // number is just a trivial example here, not required * ) // => false */ export const isResolvedWith = <A>( expected: A, equalityComparer: EqualityComparer<A> = EqualityComparer.Default ) => matchOrElse<A, boolean>({ resolved: actual => equalityComparer.equals(actual, expected), orElse: false, }) /* c8 ignore start */ /** @ignore */ export const Deferred = { notStarted, inProgress, resolved, match, matchOrElse, isUnresolved, isResolved, isInProgress, isResolvedWith, } /* c8 ignore end */
src/Deferred.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/DeferredResult.ts", "retrieved_chunk": " return getMatcherResult(matcher.inProgress, undefined)\n case \"NotStarted\":\n return getMatcherResult(matcher.notStarted, undefined)\n case \"Resolved\":\n return pipe(\n deferredResult.resolved,\n Result.match({\n ok: a => getMatcherResult(matcher.resolvedOk, a),\n err: e => getMatcherResult(matcher.resolvedErr, e),\n })", "score": 0.883093535900116 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " ? getMatcherResult(matcher.inProgress, undefined)\n : getMatcherResult(matcher.orElse, undefined)\n case \"NotStarted\":\n return objHasOptionalProp(\"notStarted\", matcher)\n ? getMatcherResult(matcher.notStarted, undefined)\n : getMatcherResult(matcher.orElse, undefined)\n case \"Resolved\":\n return pipe(\n deferredResult.resolved,\n Result.match({", "score": 0.8813557624816895 }, { "filename": "src/Result.ts", "retrieved_chunk": " case \"Ok\":\n return getMatcherResult(matcher.ok, result.ok)\n case \"Err\":\n return getMatcherResult(matcher.err, result.err)\n /* c8 ignore next 2 */\n default:\n return assertExhaustive(result)\n }\n }\n/**", "score": 0.8440326452255249 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " * })\n * )\n * ```\n */\nexport const matchOrElse =\n <A, E, R>(matcher: PartialDeferredResultMatcher<A, E, R>) =>\n (deferredResult: DeferredResult<A, E>) => {\n switch (deferredResult._tag) {\n case \"InProgress\":\n return objHasOptionalProp(\"inProgress\", matcher)", "score": 0.8162767887115479 }, { "filename": "src/Option.ts", "retrieved_chunk": " case \"None\":\n return getMatcherResult(matcher.none, void 0)\n /* c8 ignore next 2 */\n default:\n return assertExhaustive(option)\n }\n }\n/**\n * Maps the wrapped `Some` value using the given function.\n * Passes through `None` as-is.", "score": 0.8045281171798706 } ]
typescript
return resultOrValue(matcher.resolved, deferred.resolved) /* c8 ignore next 2 */ default: return assertExhaustive(deferred) as R }
/** * An `AsyncResult` represents an asynchronous computation that may either * succeed or fail (but should never throw). It is identical to `Async<Result<A, E>`. * This module simply provides convenience functions for working with that * type because they are so frequently used in real-world programming. * * Like `Async`, `AsyncResult` represents a "cold" computation that must be * explicitly invoked/started, in contrast to `Promise`s, which are "hot." * * **Note:** You can use `Async.start` to start `AsyncResult`s because they are * just `Async`s with a constrained inner value type. * * @module AsyncResult */ import { Result } from "./Result" import { Async } from "./Async" import { pipe } from "./Composition" /** * @typeParam A The type of the `Ok` branch. * @typeParam E The type of the `Err` branch. */ export interface AsyncResult<A, E> { (): Promise<Result<A, E>> } /** * Construct a new `Ok` instance. * * @group Constructors * * @returns A new `AsyncResult` containing the given ok value. */ export const ok = <A, E = never>(ok: A): AsyncResult<A, E> => () => Promise.resolve(Result.ok(ok)) /** * Construct a new `Err` instance. * * @group Constructors * * @returns A new `AsyncResult` using the given err value. */ export const err = <E, A = never>(err: E): AsyncResult<A, E> => () => Promise.resolve(Result.err(err)) /** * Maps the wrapped `Ok` value using the given function and * returns a new `AsyncResult`. Passes `Err` values through as-is. * * @group Mapping * * @example * await pipe( * AsyncResult.ok(10), * AsyncResult.map(n => n * 2), * Async.start * ) // => Result.ok(20) */ export const map = <A, B>(f: (a: A) => B) => <E>(async: AsyncResult<A, E>): AsyncResult<B, E> => () => async().then(Result.map(f)) /** * Maps the wrapped `Err` value using the given function and * returns a new `AsyncResult`. Passes `Ok` values through as-is. * * @group Mapping * * @example * await pipe( * AsyncResult.err("err"), * AsyncResult.mapErr(s => s.length), * Async.start * ) // => Result.err(3) */ export const mapErr = <Ea, Eb>(f: (a: Ea) => Eb) => <A>(async: AsyncResult<A, Ea>): AsyncResult<A, Eb> => () => async().then(Result.mapErr(f)) /** * Takes two functions: one to map an `Ok`, one to map an `Err`. * Returns a new AsyncResult with the projected value based * on which function was used. Equivalent to calling {@link map} = * followed by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, A2, E1, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => (async: AsyncResult<A1, E1>) => () => async().then(Result.mapBoth(mapOk, mapErr)) /** * Maps the wrapped `Ok` value using a given function that * also returns an AsyncResult, and flattens the result. * Also commonly known as `flatpMap`. * * @group Mapping * * @example * declare const getNumberOfLines: (fileName: string) => AsyncResult<number, Error> * declare const sendToServer: (numLines: number) => AsyncResult<{}, Error> * * await pipe( * "log.txt", // string * getNumberOfLines, // AsyncResult<number, Error> * AsyncResult.bind(sendToServer), // AsyncResult<{}, Error> * Async.start // Promise<Result<{}, Error>> * ) * // returns Result.ok({}) if everything succeeds * // otherwise returns Result.err(Error) if something * // fell down along the way */ export const bind = <A, B, E>(f: (a: A) => AsyncResult<B, E>) => (async: AsyncResult<A, E>): AsyncResult<B, E> => async () => { const result = await async() return await pipe( result, Result.match({ ok: f, err
: e => err(e), }), Async.start ) }
/** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * Projects the wrapped `Ok` value using a given _synchronous_ function * that returns a `Result` and flattens that result into a new `AsyncResult`. * Primarily useful for composing together asynchronous workflows with * synchronous functions that may also fail. (e.g., parsing a JSON string) * * @group Mapping * * @example * declare const networkRequest: (url: string) => AsyncResult<JsonValue, Error>; * declare const parseJson: (j: JsonValue) => Result<MyType, string>; * * await pipe( * url, // string * networkRequest, // AsyncResult<JsonValue, Error> * AsyncResult.bindResult(flow( * parseJson, // Result<MyType, string> * Result.mapErr(s => new Error(s)) // Result<MyType, Error> * )), // AsyncResult<MyType, Error> * Async.start // Promise<Result<MyType, Error>> * ) * // returns Result.ok(MyType) instance if everything succeeds, * // otherwise returns Result.err(Error)F if something fell over */ export const bindResult = <A, B, E>(f: (a: A) => Result<B, E>) => (async: AsyncResult<A, E>): AsyncResult<B, E> => () => async().then(Result.bind(f)) /** * Alias for {@link bindResult}. * * @group Mapping */ export const flatMapResult = bindResult /** * Use this function to "lift" a `Result` value into the `AsyncResult` type. * Essentially, this just wraps a `Result` into a lambda that returns an * immediately-resolved `Promise` containing the `Result`. * * @group Utils * @group Constructors */ export const ofResult = <A, E>(result: Result<A, E>): AsyncResult<A, E> => () => Promise.resolve(result) /** * Use this function to "lift" an `Async` computation into an `AsyncResult`. * Essentially, this just wraps the `Async`'s inner value into a `Result.ok`. * * @group Utils * @group Constructors */ export const ofAsync = <A, E = unknown>(async: Async<A>): AsyncResult<A, E> => () => async().then(a => Result.ok(a)) /* eslint-disable func-style */ /** * Converts an `Async` computation that might reject into an * Async computation that never rejects and returns a `Result`. * (Remember that an `Async` is just a lambda returning a `Promise`.) * * If the `onThrow` callback function is given, it will be used to * convert the thrown object into the Err branch. By default, the thrown * object will be `string`-ed and wrapped in an Error if it is not an Error already. * * @group Utils * * @example * ``` * declare const doHttpThing: (url: string) => Promise<number>; * * await pipe( * AsyncResult.tryCatch(() => doHttpThing("/cats")), // AsyncResult<number, Error> * AsyncResult.mapErr(e => e.message), // AsyncResult<number, string> * Async.start // Promise<Result<number, string>> * ) * // yields `Result.ok(number)` if the call succeeded * // otherwise yields `Result.err(string)` * ``` */ export function tryCatch<A>(mightThrow: Async<A>): AsyncResult<A, Error> export function tryCatch<A, E = unknown>( mightThrow: Async<A>, onThrow: (thrown: unknown) => E ): AsyncResult<A, E> export function tryCatch<A, E = unknown>( mightThrow: Async<A>, onThrow?: (err: unknown) => E ): AsyncResult<A, unknown> { return async () => { const toError = (err: unknown) => err instanceof Error ? err : Error(String(err)) try { return Result.ok(await mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } } /* eslint-enable func-style */ /** * @ignore */ interface AsyncResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } /** * Exhaustive pattern match against an `AsyncResult`. Pass a matcher * object with cases for `ok` and `err` using either raw values or * lambdas accepting the data associated with each case. * * This pattern match unwraps the inner `Result` and returns an `Async` * computation containing the result of the match. Use {@link start} to * convert the `Async` into a `Promise` which can be `await`-ed. * * @group Pattern Matching * * @example * await pipe( * AsyncResult.ok("alright!"), * AsyncResult.match({ * ok: String.capitalize, * err: "bah, humbug!", * }), * Async.start * ) // => "Alright!" */ export const match = <A, E, R>(matcher: AsyncResultMatcher<A, E, R>) => (async: AsyncResult<A, E>): Async<R> => () => async().then(Result.match(matcher)) /** * Equivalent to both Async.start or simply invoking * the AsyncResult as a function. Aliased here for convenience. * * @group Utils */ export const start = <A, E>(async: AsyncResult<A, E>) => async() /** * Execute an arbitrary side-effect on the inner `Ok` value of an `AsyncResult` * within a pipeline of functions. Useful for logging and debugging. Passes * the inner value through unchanged. Sometimes referred to as `do` or `tap`. * * The side-effect will be invoked once the underlying `Promise` has resolved. * * @param f The side-effect to execute. Should not mutate its arguments. * @returns The `AsyncResult`, unchanged. * * @group Utils */ export const tee = <A>(f: (a: A) => void) => <E>(async: AsyncResult<A, E>): AsyncResult<A, E> => Async.tee<Result<A, E>>(Result.tee(f))(async) /** * Execute an arbitrary side-effect on the inner `Err` value of an `AsyncResult` * within a pipeline of functions. Useful for logging and debugging. Passes * the inner value through unchanged. Sometimes referred to as `do` or `tap`. * * The side-effect will be invoked once the underlying `Promise` has resolved. * * @param f The side-effect to execute. Should not mutate its arguments. * @returns The `AsyncResult`, unchanged. * * @group Utils */ export const teeErr = <E>(f: (a: E) => void) => <A>(async: AsyncResult<A, E>): AsyncResult<A, E> => Async.tee<Result<A, E>>(Result.teeErr(f))(async) /* c8 ignore start */ /** @ignore */ export const AsyncResult = { ok, err, map, mapErr, mapBoth, bind, flatMap, bindResult, flatMapResult, ofResult, ofAsync, tryCatch, match, start, tee, teeErr, } /* c8 ignore end */
src/AsyncResult.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Result.ts", "retrieved_chunk": " result,\n match({\n ok: a => ok(a),\n err: e => {\n f(e)\n return err(e)\n },\n })\n )\n/**", "score": 0.9271118640899658 }, { "filename": "src/Result.ts", "retrieved_chunk": " <E>(result: Result<A, E>): Result<B, E> =>\n pipe(\n result,\n match({\n ok: a => ok(f(a)),\n err: e => err(e),\n })\n )\n/**\n * Map the inner `Err` value using the given function and", "score": 0.9045642018318176 }, { "filename": "src/Result.ts", "retrieved_chunk": " match({\n ok: a => {\n f(a)\n return ok(a)\n },\n err: e => err(e),\n })\n )\n/**\n * Allows some arbitrary side-effect function to be called", "score": 0.8996018171310425 }, { "filename": "src/Result.ts", "retrieved_chunk": " <E>(result: Result<A, E>) =>\n pipe(\n result,\n match({\n ok: a => a,\n err: a,\n })\n )\n/**\n * Return the inner `Ok` value or use the given lambda", "score": 0.8947227597236633 }, { "filename": "src/Result.ts", "retrieved_chunk": " result,\n match({\n ok: a => (refinement(a) ? ok(a) : err(onFail(a))),\n err: e => err(e),\n })\n )\n/**\n * Map the inner `Ok` value using the given function and\n * return a new `Result`. Passes `Err` values through as-is.\n *", "score": 0.8747989535331726 } ]
typescript
: e => err(e), }), Async.start ) }
/** See [Enums considered harmful](https://www.youtube.com/watch?v=jjMbPt_H3RQ) for the motivation behind this custom type. (Also worth noting is that in TypeScript 5.0 [all Enums are considered unions](https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#all-enums-are-union-enums).) Similar to [variants](variants.md) for disciminated unions, `enumOf` allows you to more easily and safely create and work with enums in TypeScript. ## Basic Example ```ts export const MyEnum = enumOf( { Dog = "Dog", Cat = "Cat", ZEBRA = 1234, } as const, // the `as const` won't be required in TypeScript 5.0 "MyEnum" // friendly name is optional; used to generate helpful parser errors ) export type MyEnum = EnumOf<typeof MyEnum> // => "Dog" | "Cat" | 1234 ``` ## Methods ### Standard enum-style accessors ```ts const dog = MyEnum.Dog // => "Dog" const zebra = MyEnum.ZEBRA // => 1234 ``` ### Values Access array of all valid values, correctly typed (but without any ordering guarantees). ```ts const myEnumValues = MyEnum.values // => ["Dog", "Cat", 1234] ``` ### Parser Get a safe parser function for this enum automagically! ```ts const parsed = MyEnum.parse("cat") // => a `Result<MyEnum, string>`, in this case `Result.ok("Cat")` ``` ### Match See `match` in the {@link Variants} module docs for more details on matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.match({ Dog: "woof woof", Cat: () => "meow", ZEBRA: "is my skin white with black stripes or black with white stripes??", }) speak(myEnum) ``` ### MatchOrElse See `matchOrElse` in the {@link Variants} module docs for more details on partial matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.matchOrElse({ Dog: "woof woof", Cat: () => "meow", orELse: "I cannot speak.", }) speak(myEnum) ``` @module Enums */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Result } from "./Result" import { String } from "./string" import { Option } from "./Option" import { pipe, flow } from "./Composition" import { Array } from "./Array" import { Identity, NonNullish } from "./prelude" /** @ignore */ type StringKeys<T extends object> = Extract<keyof T, string> /** * A plain object that serves as the definition of the enum type. * Until TypeScript 5.0 is released, you need to specify `as const` * on this object definition. */ type RawEnum = Record<string, string | number> /** @ignore */ type StringKeyValues<T extends RawEnum> = Identity<T[StringKeys<T>]> /** @ignore */ type EnumMatcher<A, R extends RawEnum> = { readonly [Label in StringKeys<R>]: (() => A) | A } /** @ignore */ type PartialEnumMatcher<A, R extends RawEnum> = Partial<EnumMatcher<A, R>> & { readonly orElse: (() => A) | A } type EnumMatch<R extends RawEnum> = <A>( matcher: EnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A type EnumMatchOrElse<R extends RawEnum> = <A>( matcher: PartialEnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A /** * The output of the {@link enumOf} function. Produces an object that serves both as * the enum as well as a namespace for helper functions related to that enum. */ type EnumModule<R extends RawEnum> = Identity< { readonly [Label in StringKeys<R>]: R[Label] } & { /** * Returns a readonly array containing the set of all possible enum values. No * guarantees are made regarding the order of items in the resultant array. */ readonly values: ReadonlyArray<StringKeyValues<R>> /** * For string enum values, the parse function will trim and coerce values to lowercase * before comparison. (This has no effect on numeric enum values.) Thus, if an * enum is defined as `'Yes' | 'No'`, this decoder will parse `'yes'`, `' yES'`, * and `' YES '` correctly into the canonical `'Yes'` enum value. */ readonly parse: (u: unknown) => Result<StringKeyValues<R>, string> /** * Use this function for an exhaustive case check that doesn't require using * a switch/case block or any kind of assertExhaustive check. */ readonly match: EnumMatch<R> /** * Use this function for a partial case check that doesn't require using * a switch/case block. */ readonly matchOrElse: EnumMatchOrElse<R> } > /** * Gets the union type representing all possible enum values. */ export type EnumOf<T> = T extends EnumModule<infer R> ? StringKeyValues<R> : [never, "Error: T must be an EnumModule"] const getParserErrorMessage = <T extends RawEnum>( enumValues: EnumModule<T>["values"], enumFriendlyName: string ) => `Must be an enum value in the set ${enumFriendlyName}{ ${enumValues.join(", ")} }` const toTrimmedLowerCase = (a: string | number) => pipe( Option.some(a), Option.refine(String.isString), Option.map(flow(String.trim, String.toLowerCase)), Option.defaultValue(a) ) const isStringOrNumber = (u: NonNullish): u is string | number => typeof u === "string" || typeof u === "number" const getParseFn = <R extends RawEnum>(enumValues: EnumModule<R>["values"], enumFriendlyName: string) => (u: unknown): Result<StringKeyValues<R>, string> => pipe( Option.ofNullish(u), Result.ofOption( () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } cannot be null/undefined` ),
Result.refine( isStringOrNumber, () => `Enum${
enumFriendlyName ? ` ${enumFriendlyName}` : "" } must be a string or number` ), Result.map(toTrimmedLowerCase), Result.bind(testVal => pipe( enumValues, Array.find(val => toTrimmedLowerCase(val) === testVal), Option.match({ some: a => Result.ok(a), none: () => Result.err( getParserErrorMessage(enumValues, enumFriendlyName) ), }) ) ) ) const isFunc = (f: unknown): f is (...args: any[]) => any => typeof f === "function" const getMatchFn = <R extends RawEnum>(raw: R): EnumMatch<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (!Object.hasOwn(matcher, enumLabel)) { throw new TypeError( `Expected a matcher containing a case for '${enumLabel}'.` ) } const matcherBranch = matcher[enumLabel] return isFunc(matcherBranch) ? matcherBranch() : matcherBranch } const getMatchOrElseFn = <R extends RawEnum>(raw: R): EnumMatchOrElse<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (Object.hasOwn(matcher, enumLabel)) { const branch = matcher[enumLabel] // eslint-disable-next-line @typescript-eslint/no-unsafe-return return isFunc(branch) ? branch() : branch } return isFunc(matcher.orElse) ? matcher.orElse() : matcher.orElse } /** * Generates an "enum module" from a raw object. For motivation behind using a custom * generative function instead of the built-in `enum` types, see [this video](https://youtu.be/jjMbPt_H3RQ). * * This function augments a raw "enum object" with several useful capabilities: `values`, `parse`, `match`, * and `matchOrElse`. * - `values` contains the list of valid enum values * - `parse` is a parser funciton auto-magically created for this enum * - `match` is a pipeable function that allows exhaustive pattern matching * - `matchOrElse` is a pipeable function that allows inexhaustive pattern matching * * @remarks * You can use the `parse` function together with `io-ts` to easily create a decoder for this enum. * * @example * ```ts * export const MyEnum = enumOf({ * Dog = 'Dog', * Cat = 'Cat', * ZEBRA = 1234, * } as const, 'MyEnum') // => friendly name optional; used to generate helpful decoder errors * export type MyEnum = EnumOf<typeof MyEnum>; //=> 'Dog' | 'Cat' | 1234 * * // Standard enum-style accessors * const dog = MyEnum.Dog; // => 'Dog' * const zebra = MyEnum.ZEBRA; // => 1234 * * // Access array of all valid values, correctly typed * const myEnumValues = MyEnum.values; // => ['Dog', 'Cat', 1234] * * // Get a decoder instance for this enum automagically * const myDecoder = MyEnum.decoder; // => a `D.Decoder<unknown, 'Dog' | 'Cat' | 1234>` * * // Match an enum value against all its cases (compiler ensures exhaustiveness) * const value: MyEnum = 'Cat'; * const matchResult = pipe( * value, * MyEnum.match({ * Dog: 'woof woof', * Cat: () => 'meow', * ZEBRA: 'is my skin white with black stripes or black with white stripes??' * }) * ) // => 'meow' * ``` */ export const enumOf = <T extends RawEnum>( raw: T, enumFriendlyName = "" ): EnumModule<T> => { const entriesWithStringKeys = Object.entries(raw).reduce( (acc, [label, value]) => ({ ...acc, [label]: value, }), {} ) const values = Object.values(raw) return { ...entriesWithStringKeys, values, parse: getParseFn(values, enumFriendlyName), match: getMatchFn(raw), matchOrElse: getMatchOrElseFn(raw), } as unknown as EnumModule<T> }
src/Enums.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Option.ts", "retrieved_chunk": " * ) // => \"\"\n */\nexport const defaultWith = <A extends NonNullish>(f: () => A) =>\n match<A, A>({\n some: a => a,\n none: f,\n })\n/**\n * Maps an `Option` using a function that returns another\n * `Option` and flattens the result. Sometimes called `flatMap`.", "score": 0.82582688331604 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n */\nexport const refine = <A extends NonNullish, B extends A>(f: Refinement<A, B>) =>\n match<A, Option<B>>({\n some: a => (f(a) ? some(a) : none),\n none: none,\n })\n/**\n * Returns the wrapped value if the `Option` is `Some`,\n * otherwise uses the given value as a default value.", "score": 0.8249678611755371 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n * pipe(\n * 56,\n * Option.ofNullish,\n * Option.filter(n => n > 50),\n * Option.map(String),\n * Option.match({\n * some: a => `${a}!`,\n * none: \"!\"\n * }),", "score": 0.8130025863647461 }, { "filename": "src/Nullable.ts", "retrieved_chunk": " * Nullable.defaultValue(\"\")\n * ) // => \"\"\n */\nexport const defaultValue =\n <A extends NonNullish>(a: A) =>\n (nullable: Nullable<A>): NonNullable<A> =>\n nullable != null ? nullable : a\n/**\n * Similar to `Option.defaultWith`. If the given nullable value is nullish,\n * computes the fallback/default value using the given function. If the given", "score": 0.8112267255783081 }, { "filename": "src/Option.ts", "retrieved_chunk": " *\n * @example\n * ```\n * const isString = (u: unknown): u is string => typeof u === \"string\"\n *\n * pipe(\n * Option.some(\"cheese\" as any), // Option<any>\n * Option.refine(isString), // Option<string> (type is narrowed by the guard)\n * Option.map(s => s.length) // Option<number> (TS infers the type of `s`)\n * ) // => Option.some(6)", "score": 0.8074259161949158 } ]
typescript
Result.refine( isStringOrNumber, () => `Enum${
/** See [Enums considered harmful](https://www.youtube.com/watch?v=jjMbPt_H3RQ) for the motivation behind this custom type. (Also worth noting is that in TypeScript 5.0 [all Enums are considered unions](https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#all-enums-are-union-enums).) Similar to [variants](variants.md) for disciminated unions, `enumOf` allows you to more easily and safely create and work with enums in TypeScript. ## Basic Example ```ts export const MyEnum = enumOf( { Dog = "Dog", Cat = "Cat", ZEBRA = 1234, } as const, // the `as const` won't be required in TypeScript 5.0 "MyEnum" // friendly name is optional; used to generate helpful parser errors ) export type MyEnum = EnumOf<typeof MyEnum> // => "Dog" | "Cat" | 1234 ``` ## Methods ### Standard enum-style accessors ```ts const dog = MyEnum.Dog // => "Dog" const zebra = MyEnum.ZEBRA // => 1234 ``` ### Values Access array of all valid values, correctly typed (but without any ordering guarantees). ```ts const myEnumValues = MyEnum.values // => ["Dog", "Cat", 1234] ``` ### Parser Get a safe parser function for this enum automagically! ```ts const parsed = MyEnum.parse("cat") // => a `Result<MyEnum, string>`, in this case `Result.ok("Cat")` ``` ### Match See `match` in the {@link Variants} module docs for more details on matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.match({ Dog: "woof woof", Cat: () => "meow", ZEBRA: "is my skin white with black stripes or black with white stripes??", }) speak(myEnum) ``` ### MatchOrElse See `matchOrElse` in the {@link Variants} module docs for more details on partial matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.matchOrElse({ Dog: "woof woof", Cat: () => "meow", orELse: "I cannot speak.", }) speak(myEnum) ``` @module Enums */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Result } from "./Result" import { String } from "./string" import { Option } from "./Option" import { pipe, flow } from "./Composition" import { Array } from "./Array" import { Identity, NonNullish } from "./prelude" /** @ignore */ type StringKeys<T extends object> = Extract<keyof T, string> /** * A plain object that serves as the definition of the enum type. * Until TypeScript 5.0 is released, you need to specify `as const` * on this object definition. */ type RawEnum = Record<string, string | number> /** @ignore */ type StringKeyValues<T extends RawEnum> = Identity<T[StringKeys<T>]> /** @ignore */ type EnumMatcher<A, R extends RawEnum> = { readonly [Label in StringKeys<R>]: (() => A) | A } /** @ignore */ type PartialEnumMatcher<A, R extends RawEnum> = Partial<EnumMatcher<A, R>> & { readonly orElse: (() => A) | A } type EnumMatch<R extends RawEnum> = <A>( matcher: EnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A type EnumMatchOrElse<R extends RawEnum> = <A>( matcher: PartialEnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A /** * The output of the {@link enumOf} function. Produces an object that serves both as * the enum as well as a namespace for helper functions related to that enum. */ type EnumModule<R extends RawEnum> = Identity< { readonly [Label in StringKeys<R>]: R[Label] } & { /** * Returns a readonly array containing the set of all possible enum values. No * guarantees are made regarding the order of items in the resultant array. */ readonly values: ReadonlyArray<StringKeyValues<R>> /** * For string enum values, the parse function will trim and coerce values to lowercase * before comparison. (This has no effect on numeric enum values.) Thus, if an * enum is defined as `'Yes' | 'No'`, this decoder will parse `'yes'`, `' yES'`, * and `' YES '` correctly into the canonical `'Yes'` enum value. */ readonly parse: (u: unknown) => Result<StringKeyValues<R>, string> /** * Use this function for an exhaustive case check that doesn't require using * a switch/case block or any kind of assertExhaustive check. */ readonly match: EnumMatch<R> /** * Use this function for a partial case check that doesn't require using * a switch/case block. */ readonly matchOrElse: EnumMatchOrElse<R> } > /** * Gets the union type representing all possible enum values. */ export type EnumOf<T> = T extends EnumModule<infer R> ? StringKeyValues<R> : [never, "Error: T must be an EnumModule"] const getParserErrorMessage = <T extends RawEnum>( enumValues: EnumModule<T>["values"], enumFriendlyName: string ) => `Must be an enum value in the set ${enumFriendlyName}{ ${enumValues.join(", ")} }` const toTrimmedLowerCase = (a: string | number) => pipe( Option.some(a), Option.refine(String.isString), Option.map(flow(String.trim, String.toLowerCase)), Option.defaultValue(a) ) const isStringOrNumber = (u: NonNullish): u is string | number => typeof u === "string" || typeof u === "number" const getParseFn = <R extends RawEnum>(enumValues: EnumModule<R>["values"], enumFriendlyName: string) => (u: unknown): Result<StringKeyValues<R>, string> => pipe( Option.ofNullish(u), Result.ofOption( () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } cannot be null/undefined` ), Result.refine( isStringOrNumber, () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } must be a string or number` ), Result.map(toTrimmedLowerCase), Result
.bind(testVal => pipe( enumValues, Array.find(val => toTrimmedLowerCase(val) === testVal), Option.match({
some: a => Result.ok(a), none: () => Result.err( getParserErrorMessage(enumValues, enumFriendlyName) ), }) ) ) ) const isFunc = (f: unknown): f is (...args: any[]) => any => typeof f === "function" const getMatchFn = <R extends RawEnum>(raw: R): EnumMatch<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (!Object.hasOwn(matcher, enumLabel)) { throw new TypeError( `Expected a matcher containing a case for '${enumLabel}'.` ) } const matcherBranch = matcher[enumLabel] return isFunc(matcherBranch) ? matcherBranch() : matcherBranch } const getMatchOrElseFn = <R extends RawEnum>(raw: R): EnumMatchOrElse<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (Object.hasOwn(matcher, enumLabel)) { const branch = matcher[enumLabel] // eslint-disable-next-line @typescript-eslint/no-unsafe-return return isFunc(branch) ? branch() : branch } return isFunc(matcher.orElse) ? matcher.orElse() : matcher.orElse } /** * Generates an "enum module" from a raw object. For motivation behind using a custom * generative function instead of the built-in `enum` types, see [this video](https://youtu.be/jjMbPt_H3RQ). * * This function augments a raw "enum object" with several useful capabilities: `values`, `parse`, `match`, * and `matchOrElse`. * - `values` contains the list of valid enum values * - `parse` is a parser funciton auto-magically created for this enum * - `match` is a pipeable function that allows exhaustive pattern matching * - `matchOrElse` is a pipeable function that allows inexhaustive pattern matching * * @remarks * You can use the `parse` function together with `io-ts` to easily create a decoder for this enum. * * @example * ```ts * export const MyEnum = enumOf({ * Dog = 'Dog', * Cat = 'Cat', * ZEBRA = 1234, * } as const, 'MyEnum') // => friendly name optional; used to generate helpful decoder errors * export type MyEnum = EnumOf<typeof MyEnum>; //=> 'Dog' | 'Cat' | 1234 * * // Standard enum-style accessors * const dog = MyEnum.Dog; // => 'Dog' * const zebra = MyEnum.ZEBRA; // => 1234 * * // Access array of all valid values, correctly typed * const myEnumValues = MyEnum.values; // => ['Dog', 'Cat', 1234] * * // Get a decoder instance for this enum automagically * const myDecoder = MyEnum.decoder; // => a `D.Decoder<unknown, 'Dog' | 'Cat' | 1234>` * * // Match an enum value against all its cases (compiler ensures exhaustiveness) * const value: MyEnum = 'Cat'; * const matchResult = pipe( * value, * MyEnum.match({ * Dog: 'woof woof', * Cat: () => 'meow', * ZEBRA: 'is my skin white with black stripes or black with white stripes??' * }) * ) // => 'meow' * ``` */ export const enumOf = <T extends RawEnum>( raw: T, enumFriendlyName = "" ): EnumModule<T> => { const entriesWithStringKeys = Object.entries(raw).reduce( (acc, [label, value]) => ({ ...acc, [label]: value, }), {} ) const values = Object.values(raw) return { ...entriesWithStringKeys, values, parse: getParseFn(values, enumFriendlyName), match: getMatchFn(raw), matchOrElse: getMatchOrElseFn(raw), } as unknown as EnumModule<T> }
src/Enums.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Option.ts", "retrieved_chunk": " * ) // => \"\"\n */\nexport const defaultWith = <A extends NonNullish>(f: () => A) =>\n match<A, A>({\n some: a => a,\n none: f,\n })\n/**\n * Maps an `Option` using a function that returns another\n * `Option` and flattens the result. Sometimes called `flatMap`.", "score": 0.8110153675079346 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n */\nexport const refine = <A extends NonNullish, B extends A>(f: Refinement<A, B>) =>\n match<A, Option<B>>({\n some: a => (f(a) ? some(a) : none),\n none: none,\n })\n/**\n * Returns the wrapped value if the `Option` is `Some`,\n * otherwise uses the given value as a default value.", "score": 0.798649251461029 }, { "filename": "src/Result.ts", "retrieved_chunk": " *\n * This API has been optimized for use with left-to-right function composition\n * using `pipe` and `flow`.\n *\n * @example\n * ```\n * pipe(\n * Result.tryCatch(() => readFileMightThrow()),\n * Result.mapErr(FileError.create),\n * Result.bind(fileText => pipe(", "score": 0.7979933619499207 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": " const result = await async()\n return await pipe(\n result,\n Result.match({\n ok: f,\n err: e => err(e),\n }),\n Async.start\n )\n }", "score": 0.7935774326324463 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n * pipe(\n * 56,\n * Option.ofNullish,\n * Option.filter(n => n > 50),\n * Option.map(String),\n * Option.match({\n * some: a => `${a}!`,\n * none: \"!\"\n * }),", "score": 0.7924319505691528 } ]
typescript
.bind(testVal => pipe( enumValues, Array.find(val => toTrimmedLowerCase(val) === testVal), Option.match({
/** * A suite of useful functions for working with readonly arrays. These functions * provide a curried API that works seamlessly with right-to-left function * composition and preserve the `readonly` type. * * @module Array */ import { Predicate, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { Result } from "./Result" import { pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" import { OrderingComparer } from "./OrderingComparer" import { NonEmptyArray } from "./NonEmptyArray" /* eslint-disable func-style */ /** * Curried and readonly version of the built-in `filter`. * Accepts a plain predicate function or a refinement * function (a.k.a. type guard). * * @group Filtering */ export function filter<A, B extends A>( refinement: Refinement<A, B> ): (as: readonly A[]) => readonly B[] export function filter<A>( predicate: Predicate<A> ): <B extends A>(bs: readonly B[]) => readonly B[] export function filter<A>(predicate: Predicate<A>): (as: readonly A[]) => readonly A[] export function filter<A>(f: Predicate<A>) { return <B extends A>(as: readonly B[]) => as.filter(f) } /* eslint-enable func-style */ /** * Like {@link filter}, but the predicate function also accepts the * index of the element as an argument. * * @group Filtering */ export const filteri = <A>(f: (a: A, i: number) => boolean) => (as: readonly A[]): readonly A[] => as.filter(f) /** * Curried and readonly version of the built-in `map`. * * @group Mapping */ export const map = <A, B>(f: (a: A) => B) => (as: readonly A[]): readonly B[] => as.map(f) /** * Like {@link map} but the map function also accepts the * index of the element as an argument. * * @group Mapping */ export const mapi = <A, B>(f: (a: A, i: number) => B) => (as: readonly A[]): readonly B[] => as.map(f) /** * Maps each value of the array into an `Option`, and keeps only the inner * values of those `Option`s that are`Some`. Essentially, this is a combined map + * filter operation where each element of the array is mapped into an `Option` * and an `isSome` check is used as the filter function. * * @group Mapping * * @example * pipe( * [32, null, 55, undefined, 89], // (number | null | undefined)[] * Array.choose(x => pipe( * x, // number | null | undefined * Option.ofNullish, // Option<number> * Option.map(String) // Option<string> * )) // string[] * ) // => ["32", "55", "89"] */ export const choose = <A, B extends NonNullish>(f: (a: A) => Option<B>) => (as: readonly A[]): readonly B[] => { const bs: B[] = [] for (let i = 0; i < as.length; i++) { const maybeB = f(as[i]) if (Option.isSome(maybeB)) { bs.push(maybeB.some) } } return bs } /** * Like {@link choose}, but maps each value of the array into a `Result`, * and keeps only the values where the projection returns `Ok`. Essentially, * this is a combined map + filter operation where each element of the array * is mapped into an `Result` and an `isOk` check is used as the filter function. * * @group Mapping * * @example * pipe( * [32, null, 55, undefined, 89], // (number | null | undefined)[] * Array.chooseR(x => pipe( * x, // number | null | undefined * Option.ofNullish, // Option<number> * Option.map(String), // Option<string> * Result.ofOption(() => "err") // Result<string, string> * )) // string[] * ) // => ["32", "55", "89"] */ export const chooseR = <A, E, B>(f: (a: A) => Result<B, E>) => (as: readonly A[]): readonly B[] => { const bs: B[] = [] for (let i = 0; i < as.length; i++) { const result = f(as[i]) if (Result.isOk(result)) { bs.push(result.ok) } } return bs } /** * Get the first element of the array (wrapped in `Some`) if * non-empty, otherwise `None`. * * @group Utils * @group Pattern Matching * * @example * ```ts * Array.head([]) // => `Option.none` * Array.head([1, 2, 3]) // => `Option.some(1)` * ``` */ export const head = <A extends NonNullish>(as: readonly A[]): Option<A> => as.length > 0 ? Option.some(as[0]) : Option.none /** * Alias of {@link head}. * * @group Utils * @group Pattern Matching */ export const first = head /** * Get a new array containing all values except the first * one (wrapped in `Some`) if non-empty, otherwise `None`. * * @group Utils * @group Pattern Matching * * @example * pipe( * [1, 2, 3, 4], * Array.tail * ) // => Option.some([2, 3, 4]) */ export const tail = <A>(as: readonly A[]): Option<readonly A[]> => { if (as.length === 0) { return Option.none } // eslint-disable-next-line @typescript-eslint/no-unused-vars const [_, ...tail] = as return Option.some(tail) } /** * Get the first `n` elements of the array. Will return the entire * array if `n` is greater than the length of the array. * * @param count is normalized to a non-negative integer * * @group Utils * * @example * pipe( * [1, 2, 3, 4, 5, 6], * Array.take(3) * ) // => [1, 2, 3] */ export const take = (count: number) => <A>(as: readonly A[]): readonly A[] => { const c = count <= 0 ? 0 : Math.floor(count) if (c > as.length) { return as } const out: A[] = [] for (let i = 0; i < as.length && i < c; i++) { out.push(as[i]) } return out } /** * Get the remaining elements of the array * after skipping `n` elements. Returns empty if the * skip count goes past the end of the array. * * @group Utils * * @param count is normalized to a non-negative integer * * @example * pipe( * [1, 2, 3, 4, 5, 6], * Array.skip(3) * ) // => [4, 5, 6] */ export const skip = (count: number) => <A>(as: readonly A[]): readonly A[] => { const c = count <= 0 ? 0 : Math.floor(count) if (c >= as.length) { return [] } const out: A[] = [] for (let i = c; i < as.length; i++) { out.push(as[i]) } return out } /** * Curried and readonly version of the built-in `Array.prototype.reduce`. Takes * the initial value first instead of last. * * @group Utils * @group Folding */ export const reduce = <A, B>(initialValue: B, reducer: (acc: B, next: A) => B) => (as: readonly A[]): B => as.reduce(reducer, initialValue) /** * Curried and readonly version of the built-in `Array.prototype.reduceRight`. * Takes the initial value first instead of last. * * @group Utils * @group Folding */ export const reduceRight = <A, B>(initialValue: B, reducer: (acc: B, next: A) => B) => (as: readonly A[]): B => as.reduceRight(reducer, initialValue) const isRawValue = <A, R>(caseFn: R | ((ok: A) => R)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * @ignore */ interface ArrayMatcher<A, R> { empty: (() => R) | R
nonEmpty: ((as: NonEmptyArray<A>) => R) | R }
/** * Exhaustive pattern match against an array to "unwrap" its values. Provide * a matcher object to handle both the `empty` and `nonEmpty` cases. * The matcher can use lambdas or raw values. In the `nonEmpty` case, * the lambda will be given a `NonEmptyArray`. * * @group Pattern Matching * * @example * ```ts * pipe( * ["a", "b"], * Array.match({ * empty: () => "default", * nonEmpty: Array.reduceRight("", (a, b) => `${a}${b}`) * }) * ) // => "ba" * ``` */ export const match = <A, R>(matcher: ArrayMatcher<A, R>) => (as: readonly A[]): R => as.length > 0 ? getMatcherResult(matcher.nonEmpty, as as NonEmptyArray<A>) : getMatcherResult(matcher.empty, undefined) /** * Type guard that tests whether the given array is equivalent * to the empty tuple type. * * @group Type Guards * @group Utils */ export const isEmpty = <A>(as: readonly A[]): as is readonly [] => as.length === 0 /** * Type guard that tests whether the given array is a `NonEmptyArray` * * @group Type Guards * @group Utils */ export const isNonEmpty = <A>(as: readonly A[]): as is NonEmptyArray<A> => as.length > 0 /** * Also commonly known as `flatMap`. Maps each element of the array * given a function that itself returns an array, then flattens the result. * * @group Mapping * * @example * pipe( * [1, 2, 3], * Array.bind(n => [n, n]) * ) // => [1, 1, 2, 2, 3, 3] */ export const bind = <A, B>(f: (a: A) => readonly B[]) => (as: readonly A[]): readonly B[] => as.flatMap(f) /** * Alias of {@link bind}. * * @group Mapping */ export const flatMap = bind /** * Add an element to the _end_ of an array. Always returns * a `NonEmptyArray`. * * @group Utils */ export const append = <A>(a: A) => (as: readonly A[]): NonEmptyArray<A> => [...as, a] as unknown as NonEmptyArray<A> /** * Also known as `cons`. Insert an element at the beginning * of an array. Always returns a `NonEmptyArray`. * * @group Utils * * @example * pipe( * [2, 3], * Array.prepend(1) * ) // => [1, 2, 3] */ export const prepend = <A>(a: A) => (as: readonly A[]): NonEmptyArray<A> => [a, ...as] /** * Return a Map of keys to groups, where the selector function * is used to generate a string key that determines in which group * each array element is placed. * * @group Grouping * @group Utils * * @example * pipe( * [1, 2, 1, 2, 3, 3, 5], * Array.groupBy(String) * ) * // structurally equivalent to * new Map([ * ['1', [1, 1]], * ['2', [2, 2]], * ['3', [3, 3]], * ['5', [5]] * ]) */ export const groupBy = <A>(selector: (a: A) => string) => (as: readonly A[]): ReadonlyMap<string, NonEmptyArray<A>> => { const groups: Map<string, NonEmptyArray<A>> = new Map() as.forEach(a => { const key = selector(a) return groups.has(key) ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion groups.set(key, pipe(groups.get(key)!, append(a))) : groups.set(key, [a]) }) return groups } /** * Add an array of values to the _end_ of the subsequently * passed (partially applied) array, in a way that makes sense * when reading top-to-bottom/left-to-right using `pipe`. * * @group Utils * * @example * pipe( * [1, 2], * Array.concat([3, 4]) * ) // => [1, 2, 3, 4] */ export const concat = <A>(addToEnd: readonly A[]) => (as: readonly A[]): readonly A[] => [...as, ...addToEnd] /** * Like {@link concat}, except this adds an array of values to the * _beginning_ of the subsequently (partially applied) array, * in a way that makes more sense when _not_ using `pipe`. * * @group Utils * * @example * ```ts * // Reads "backwards" when used with `pipe` * pipe( * ["a", "b"], * Array.concatFirst(["c", "d"]) * ) // => ["c", "d", "a", "b"] * // Reads better when *not* used with `pipe` * Array.concatFirst(["a", "b"])(["c", "d"]) // => ["a", "b", "c", "d"] * ``` */ export const concatFirst = <A>(addToFront: readonly A[]) => (as: readonly A[]): readonly A[] => [...addToFront, ...as] /** * Returns true if at least one element of the array * satisfies the given predicate. Curried version of * `Array.prototype.some`. * * @group Utils */ export const exists = <A>(predicate: (a: A) => boolean) => (as: readonly A[]): boolean => as.some(predicate) /** * Alias of {@link exists}. * * @group Utils */ export const some = exists /** * Equivalent to calling `Array.prototype.flat()` with a depth of 1. * * @group Utils */ export const flatten = <A>(as: readonly (readonly A[])[]): readonly A[] => as.flat() /** * Split an array into chunks of a specified size. The final * chunk will contain fewer elements than the specified size if * the array is not evenly divisible by the specified size. * * @remarks * **Note:** Will return `[]`, _not_ `[[]]` if given an empty array. * * @param maxChunkSize Normalized to a positive integer. * * @example * pipe( * ["a", "b", "c", "d", "e"], * Array.chunk(2) * ) // => [["a", "b"], ["c", "d"], ["e"]] * * @group Utils * @group Grouping */ export const chunk = (maxChunkSize: number) => <A>(as: readonly A[]): readonly NonEmptyArray<A>[] => { if (isEmpty(as)) { return [] } const chunkSize = maxChunkSize <= 1 ? 1 : Math.floor(maxChunkSize) const numChunks = Math.ceil(as.length / chunkSize) // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const chunks: A[][] = [...globalThis.Array(numChunks)].map(() => []) let chunkIndex = 0 for (let i = 0; i < as.length; i++) { if (i !== 0 && i % chunkSize === 0) { chunkIndex++ } chunks[chunkIndex].push(as[i]) } return chunks as unknown as readonly NonEmptyArray<A>[] } /** * Get the length of an array. * * @group Utils */ export const length = <A>(as: readonly A[]) => as.length /** * Returns true if the given element is in the array. * Optionally, pass an `EqualityComparer` to use. Uses * reference (triple equals) equality by default. * * @group Utils */ export const contains = <A>(a: A, equalityComparer: EqualityComparer<A> = EqualityComparer.Default) => (as: readonly A[]): boolean => { if (isEmpty(as)) { return false } const predicate = (test: A) => equalityComparer.equals(a, test) return as.some(predicate) } /** * Return a new array containing only unique values. If * passed, uses the `EqualityComparer` to test uniqueness. * Defaults to using reference equality (triple equals). * * @group Utils * * @example * pipe( * [3, 2, 1, 2, 1, 4, 9], * Array.uniq() * ) // => [3, 2, 1, 4, 9] */ export const uniq = <A>(equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } const out: A[] = [] as.forEach(a => { if (!contains(a, equalityComparer)(out)) { out.push(a) } }) return out } /** * Returns a new array containing only unique values as determined * by mapping each element with the given function and optionally * passing an equality comparer to use on the mapped elements. * Defaults to using reference equality (triple equals). * * @group Utils * * @example * pipe( * [{ name: "Rufus" }, { name: "Rex" }, { name: "Rufus" }], * Array.uniqBy(p => p.name) * ) // => [{ name: "Rufus" }, { name: "Rex" }] */ export const uniqBy = <A, B>(f: (a: A) => B, equalityComparer?: EqualityComparer<B>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } const out: A[] = [] const projections: B[] = [] as.forEach(a => { const projected = f(a) if (!contains(projected, equalityComparer)(projections)) { projections.push(projected) out.push(a) } }) return out } /** * Get a new array with elements sorted. If given, will use the * `OrderingComparer`. Otherwise, uses the default JavaScript ASCII-based sort. * * @group Utils * * @example * declare const petByNameComparer: OrderingComparer<Pet> * * const pets: readonly Pet[] = [ * { name: "Fido" }, * { name: "Albus" }, * { name: "Rex" }, * { name: "Gerald" } * ] * * pipe( * pets, * Array.sort(petByNameComparer), * Array.map(p => p.name) * ) // => [ "Albus", "Fido", "Gerald", "Rex" ] */ export const sort = <A>(orderingComparer?: OrderingComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } return as.slice(0).sort(orderingComparer?.compare) } /** * Get a new array with elements sorted based on the sort-order * of each mapped element produced by the given mapping function. * If given, will use the `OrderingComparer`. Otherwise, defaults to an * OrderingComparer that `String`s the mapped element and uses the * default ASCII-based sort. * * @group Utils */ export const sortBy = <A, B>( f: (a: A) => B, orderingComparer: OrderingComparer<B> = OrderingComparer.Default ) => (as: readonly A[]): readonly A[] => isEmpty(as) ? [] : as.slice(0).sort((o1: A, o2: A) => orderingComparer.compare(f(o1), f(o2))) /** * Get a new array with the elements in reverse order. * * @group Utils */ export const reverse = <A>(as: readonly A[]): readonly A[] => as.slice(0).reverse() /** * Get the _first_ element in the array (wrapped in a `Some`) that * returns `true` for the given predicate, or `None` if no such * element exists. * * @group Utils */ export const find = <A extends NonNullish>(predicate: Predicate<A>) => (as: readonly A[]): Option<A> => Option.ofNullish(as.find(predicate)) /** * Get the _first_ index of the array (wrapped in a `Some`) for * which the element at that index returns true for the given predicate, * or `None` if no such index/element exists. * * @group Utils */ export const findIndex = <A>(predicate: Predicate<A>) => (as: readonly A[]): Option<number> => { const result = as.findIndex(predicate) return result < 0 ? Option.none : Option.some(result) } /** * Get a new array containing only those elements that are not * in the given `excludeThese` array. If given, will use the * EqualityComparer. Otherwise, defaults to reference equality * (triple equals). * * @group Utils * * @example * pipe( * [1, 2, 3, 4, 5], * Array.except([2, 5]) * ) // => [1, 3, 4] */ export const except = <A>(excludeThese: readonly A[], equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => { if (isEmpty(as)) { return [] } if (isEmpty(excludeThese)) { return as } const out: A[] = [] for (let i = 0; i < as.length; i++) { if (!pipe(excludeThese, contains(as[i], equalityComparer))) { out.push(as[i]) } } return out } /** * Get a new array containing the set union of two arrays, defined as the * set of elements contained in both arrays. **Remember:** sets only contain * unique elements. If you just need to join two arrays together, use {@link concat}. * * @group Utils */ export const union = <A>(unionWith: readonly A[], equalityComparer?: EqualityComparer<A>) => (as: readonly A[]): readonly A[] => isEmpty(unionWith) && isEmpty(as) ? [] : pipe(as, concat(unionWith), uniq(equalityComparer)) /** * Get an {@link EqualityComparer} that represents structural equality for an array * of type `A` by giving this function an `EqualityComparer` for each `A` element. * * @group Equality * @group Utils * * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison. * * @returns A new `EqualityComparer` instance * * @example * const eq = Array.getEqualityComparer(EqualityComparer.Number) * eq.equals([1, 2, 3], [1, 2, 3]) // => true * eq.equals([1, 3], [3, 1]) // => false */ export const getEqualityComparer = <A>({ equals, }: EqualityComparer<A>): EqualityComparer<readonly A[]> => EqualityComparer.ofEquals((arr1, arr2) => { if (isEmpty(arr1) && isEmpty(arr2)) { return true } if (arr1.length !== arr2.length) { return false } for (let i = 0; i < arr1.length; i++) { if (!equals(arr1[i], arr2[i])) { return false } } return true }) /** * Does not affect the passed array at runtime. (Effectively executes an identity * function) Removes the `readonly` part of the **type** only. * * @group Utils */ export const asMutable = <A>(as: readonly A[]) => as as A[] /** * Execute an arbitrary side effect for each element of the array. Essentially a * curried version of the built-in `forEach` method. * * @group Utils */ export const iter = <A>(f: (a: A) => void) => (as: readonly A[]): void => as.forEach(a => f(a)) /** @ignore */ export const Array = { filter, filteri, map, mapi, bind, flatMap, choose, chooseR, head, first, tail, take, skip, reduce, reduceRight, match, isEmpty, isNonEmpty, append, prepend, groupBy, concat, concatFirst, exists, some, flatten, chunk, length, contains, uniq, uniqBy, sort, sortBy, reverse, find, findIndex, except, union, getEqualityComparer, asMutable, iter, } /* c8 ignore end */
src/Array.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Result.ts", "retrieved_chunk": "interface ResultMatcher<A, E, R> {\n readonly ok: R | ((ok: A) => R)\n readonly err: R | ((err: E) => R)\n}\nconst isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R =>\n typeof caseFn !== \"function\"\nconst getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) =>\n isRawValue(match) ? match : match(arg)\n/**\n * Exhaustive pattern match against a `Result` to \"unwrap\" its inner", "score": 0.9179491996765137 }, { "filename": "src/Option.ts", "retrieved_chunk": " readonly some: R | ((some: A) => R)\n readonly none: R | (() => R)\n}\nconst isRawValue = <A, R>(caseFn: R | ((ok: A) => R)): caseFn is R =>\n typeof caseFn !== \"function\"\nconst getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) =>\n isRawValue(match) ? match : match(arg)\n/**\n * Exhaustively pattern match against an `Option` in order\n * to \"unwrap\" the inner value. Provide either a raw value", "score": 0.9149748682975769 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": "}\nconst isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R =>\n typeof caseFn !== \"function\"\nconst getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) =>\n isRawValue(match) ? match : match(arg)\nconst objHasOptionalProp = <T extends object, P extends keyof T>(\n prop: P,\n obj: T\n): obj is Identity<T & Required<{ [key in P]: T[P] }>> => Object.hasOwn(obj, prop)\n/**", "score": 0.906818151473999 }, { "filename": "src/Option.ts", "retrieved_chunk": " * none: 0,\n * })\n * ) // => 84\n */\nexport const match =\n <A extends NonNullish, R>(matcher: OptionMatcher<A, R>) =>\n (option: Option<A>) => {\n switch (option._tag) {\n case \"Some\":\n return getMatcherResult(matcher.some, option.some)", "score": 0.8729639053344727 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n */\nexport const refine = <A extends NonNullish, B extends A>(f: Refinement<A, B>) =>\n match<A, Option<B>>({\n some: a => (f(a) ? some(a) : none),\n none: none,\n })\n/**\n * Returns the wrapped value if the `Option` is `Some`,\n * otherwise uses the given value as a default value.", "score": 0.8687906265258789 } ]
typescript
nonEmpty: ((as: NonEmptyArray<A>) => R) | R }
/** * The `Deferred` type represents the state of some asynchronous operation. The * operation can either be `NotStarted`, `InProgress`, or `Resolved`. When the * operation is resolved, it has some data attached to it that represents the * outcome of the asyncrhonous work. * * This type is frequently used with `Result` as the data of the `Resolved` * branch, because it is a common situation to model the outcome of an asynchronous * operation that can fail. * * This type is especially helpful in Redux stores (or in the React `useReducer` * state) because it allows you to determinstically model the state of an async * operation as one value. I.e., instead of using separate flags that are * _implicitly_ related to each other (e.g., `notStarted`, `loading`, `result`), * you know for a fact that the async work can only be in one of three states, * and the data present on the resolved state is _only_ present on the resolved * state. * * @example * declare const def: Deferred<ApiResponse> * * pipe( * def, * Deferred.match({ * notStarted: "Not Started", * inProgress: "In Progress", * resolved: response => response.body * }) * ) * * @module Deferred */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive } from "./prelude" import { pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" /** The `NotStarted` type. */
export interface NotStarted extends Tagged<"NotStarted", object> {}
/** The `InProgress` type. */ export interface InProgress extends Tagged<"InProgress", object> {} /** The `Resolved` type. */ export interface Resolved<A> extends Tagged<"Resolved", { resolved: A }> {} /** A discriminated union type representing a `Deferred` value. */ export type Deferred<A> = NotStarted | InProgress | Resolved<A> /** * The static `NotStarted` instance. * * @group Constructors */ export const notStarted: Deferred<never> = Object.freeze({ _tag: "NotStarted" }) /** * The static `InProgress` instance. * * @group Constructors */ export const inProgress: Deferred<never> = Object.freeze({ _tag: "InProgress" }) /** * Construct a new `Resolved` instance with the given data attached. * * @param a The data that will be wrapped in the `Deferred`. * * @group Constructors */ export const resolved = <A>(a: A): Deferred<A> => ({ _tag: "Resolved", resolved: a }) /** @ignore */ interface DeferredMatcher<A, R> { readonly notStarted: (() => R) | R readonly inProgress: (() => R) | R readonly resolved: ((a: A) => R) | R } /** @ignore */ interface PartialDeferredMatcher<A, R> extends Partial<DeferredMatcher<A, R>> { readonly orElse: (() => R) | R } type Func<T> = (...args: any[]) => T type FuncOrValue<T> = Func<T> | T const resultOrValue = <T>(f: FuncOrValue<T>, ...args: any[]) => { const isFunc = (f: FuncOrValue<T>): f is Func<T> => typeof f === "function" // eslint-disable-next-line @typescript-eslint/no-unsafe-argument return isFunc(f) ? f(...args) : f } /** * Exhaustively pattern match against a `Deferred` value. Provide either * a value or a lambda to use for each case. If you provide a lambda to the * `resolved` case, it will be given the data associated with the `Resolved` * instance. * * See docs for {@link Deferred} for example. * * @param matcher The matcher object to use. * * @group Pattern Matching * * @example * ``` * declare const def: Deferred<MyApiResponse> * pipe( * def, * Deferred.match({ * notStarted: "", * inProgress: "Loading...", * resolved: resp => resp?.body ?? "" * }) * ) // => the string produced in each case, depending on the value of `def` * ``` */ export const match = <A, R>(matcher: DeferredMatcher<A, R>) => (deferred: Deferred<A>) => { switch (deferred._tag) { case "NotStarted": return resultOrValue(matcher.notStarted) case "InProgress": return resultOrValue(matcher.inProgress) case "Resolved": return resultOrValue(matcher.resolved, deferred.resolved) /* c8 ignore next 2 */ default: return assertExhaustive(deferred) as R } } /** * Non-exhaustive pattern match against a `Deferred`. Provide a lambda or raw value * to return for the various cases. (But don't specify all the cases. You should use * {@link match} if you want exhaustive case checking.) Then also provide a raw value * or lambda to use for the `orElse` case if the check falls through all other cases. * * @group Pattern Matching * * @example * ``` * declare const def: Deferred<number> * pipe( * def, * Deferred.matchOrElse({ * resolved: statusCode => `Status: ${statusCode}`, * orElse: 'Not Finished' // effectively captures both "in progress" and "not started" cases together * }) * ) * ``` */ export const matchOrElse = <A, R>(matcher: PartialDeferredMatcher<A, R>) => (deferred: Deferred<A>) => { switch (deferred._tag) { case "NotStarted": return resultOrValue( matcher.notStarted != null ? matcher.notStarted : matcher.orElse ) case "InProgress": return resultOrValue( matcher.inProgress != null ? matcher.inProgress : matcher.orElse ) case "Resolved": return matcher.resolved != null ? resultOrValue(matcher.resolved, deferred.resolved) : resultOrValue(matcher.orElse) /* c8 ignore next 2 */ default: return resultOrValue(matcher.orElse) } } /** * Get whether the `Deferred` is either in progress or not started. * * @group Utils */ export const isUnresolved: <A>(deferred: Deferred<A>) => boolean = matchOrElse({ resolved: false, orElse: true, }) /** * Gets whether the `Deferred` is in progress. * * @group Utils */ export const isInProgress = <A>(deferred: Deferred<A>): deferred is InProgress => pipe( deferred, matchOrElse({ inProgress: true, orElse: false, }) ) /** * Gets whether the `Deferred` is resolved. * * @group Utils */ export const isResolved = <A>(deferred: Deferred<A>): deferred is Resolved<A> => pipe( deferred, matchOrElse({ resolved: true, orElse: false, }) ) /** * Gets whether the `Deferred` is resolved with data equal to a specific value. * Uses the `EqualityComparer` if given, otherwise defaults to reference (triple * equals) equality. * * @group Pattern Matching * @group Utils * * @example * pipe( * Deferred.resolved(101), * Deferred.isResolvedWith(100, EqualityComparer.Number) * // number is just a trivial example here, not required * ) // => false */ export const isResolvedWith = <A>( expected: A, equalityComparer: EqualityComparer<A> = EqualityComparer.Default ) => matchOrElse<A, boolean>({ resolved: actual => equalityComparer.equals(actual, expected), orElse: false, }) /* c8 ignore start */ /** @ignore */ export const Deferred = { notStarted, inProgress, resolved, match, matchOrElse, isUnresolved, isResolved, isInProgress, isResolvedWith, } /* c8 ignore end */
src/Deferred.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Variants.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-unsafe-call */\n/* eslint-disable @typescript-eslint/no-unsafe-argument */\nimport { Identity } from \"./prelude\"\nimport { String } from \"./string\"\n/**************\n * Helper Types\n ***************/\ntype DefaultDiscriminant = \"_tag\"\ntype DefaultScope = \"\"\ntype Func = (...args: any[]) => any", "score": 0.8664790391921997 }, { "filename": "src/Option.ts", "retrieved_chunk": " * console.info\n * ) // logs \"56!\"\n * ```\n *\n * @module Option\n */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { Tagged, assertExhaustive, Refinement, NonNullish } from \"./prelude\"\nimport { pipe } from \"./Composition\"\nimport { EqualityComparer } from \"./EqualityComparer\"", "score": 0.8508009910583496 }, { "filename": "src/Enums.ts", "retrieved_chunk": " orELse: \"I cannot speak.\",\n})\nspeak(myEnum)\n```\n@module Enums\n*/\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Result } from \"./Result\"\nimport { String } from \"./string\"\nimport { Option } from \"./Option\"", "score": 0.8282497525215149 }, { "filename": "src/Result.ts", "retrieved_chunk": " * @module Result\n */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { Tagged, assertExhaustive, Refinement, NonNullish } from \"./prelude\"\nimport { Option } from \"./Option\"\nimport { flow, pipe } from \"./Composition\"\nimport { EqualityComparer } from \"./EqualityComparer\"\nexport interface Ok<A> extends Tagged<\"Ok\", { ok: A }> {}\nexport interface Err<E> extends Tagged<\"Err\", { err: E }> {}\nexport type Result<A, E> = Ok<A> | Err<E>", "score": 0.8118826746940613 }, { "filename": "src/Variants.ts", "retrieved_chunk": " },\n discriminantProperty,\n scope\n)\ntype CustomPet = VariantOf<typeof CustomPet>\n```\n@module Variants\n*/\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-return */", "score": 0.779554009437561 } ]
typescript
export interface NotStarted extends Tagged<"NotStarted", object> {}
/** See [Enums considered harmful](https://www.youtube.com/watch?v=jjMbPt_H3RQ) for the motivation behind this custom type. (Also worth noting is that in TypeScript 5.0 [all Enums are considered unions](https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#all-enums-are-union-enums).) Similar to [variants](variants.md) for disciminated unions, `enumOf` allows you to more easily and safely create and work with enums in TypeScript. ## Basic Example ```ts export const MyEnum = enumOf( { Dog = "Dog", Cat = "Cat", ZEBRA = 1234, } as const, // the `as const` won't be required in TypeScript 5.0 "MyEnum" // friendly name is optional; used to generate helpful parser errors ) export type MyEnum = EnumOf<typeof MyEnum> // => "Dog" | "Cat" | 1234 ``` ## Methods ### Standard enum-style accessors ```ts const dog = MyEnum.Dog // => "Dog" const zebra = MyEnum.ZEBRA // => 1234 ``` ### Values Access array of all valid values, correctly typed (but without any ordering guarantees). ```ts const myEnumValues = MyEnum.values // => ["Dog", "Cat", 1234] ``` ### Parser Get a safe parser function for this enum automagically! ```ts const parsed = MyEnum.parse("cat") // => a `Result<MyEnum, string>`, in this case `Result.ok("Cat")` ``` ### Match See `match` in the {@link Variants} module docs for more details on matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.match({ Dog: "woof woof", Cat: () => "meow", ZEBRA: "is my skin white with black stripes or black with white stripes??", }) speak(myEnum) ``` ### MatchOrElse See `matchOrElse` in the {@link Variants} module docs for more details on partial matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.matchOrElse({ Dog: "woof woof", Cat: () => "meow", orELse: "I cannot speak.", }) speak(myEnum) ``` @module Enums */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Result } from "./Result" import { String } from "./string" import { Option } from "./Option" import { pipe, flow } from "./Composition" import { Array } from "./Array" import { Identity, NonNullish } from "./prelude" /** @ignore */ type StringKeys<T extends object> = Extract<keyof T, string> /** * A plain object that serves as the definition of the enum type. * Until TypeScript 5.0 is released, you need to specify `as const` * on this object definition. */ type RawEnum = Record<string, string | number> /** @ignore */ type StringKeyValues<T extends RawEnum> = Identity<T[StringKeys<T>]> /** @ignore */ type EnumMatcher<A, R extends RawEnum> = { readonly [Label in StringKeys<R>]: (() => A) | A } /** @ignore */ type PartialEnumMatcher<A, R extends RawEnum> = Partial<EnumMatcher<A, R>> & { readonly orElse: (() => A) | A } type EnumMatch<R extends RawEnum> = <A>( matcher: EnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A type EnumMatchOrElse<R extends RawEnum> = <A>( matcher: PartialEnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A /** * The output of the {@link enumOf} function. Produces an object that serves both as * the enum as well as a namespace for helper functions related to that enum. */ type EnumModule<R extends RawEnum> = Identity< { readonly [Label in StringKeys<R>]: R[Label] } & { /** * Returns a readonly array containing the set of all possible enum values. No * guarantees are made regarding the order of items in the resultant array. */ readonly values: ReadonlyArray<StringKeyValues<R>> /** * For string enum values, the parse function will trim and coerce values to lowercase * before comparison. (This has no effect on numeric enum values.) Thus, if an * enum is defined as `'Yes' | 'No'`, this decoder will parse `'yes'`, `' yES'`, * and `' YES '` correctly into the canonical `'Yes'` enum value. */ readonly parse: (u: unknown) => Result<StringKeyValues<R>, string> /** * Use this function for an exhaustive case check that doesn't require using * a switch/case block or any kind of assertExhaustive check. */ readonly match: EnumMatch<R> /** * Use this function for a partial case check that doesn't require using * a switch/case block. */ readonly matchOrElse: EnumMatchOrElse<R> } > /** * Gets the union type representing all possible enum values. */ export type EnumOf<T> = T extends EnumModule<infer R> ? StringKeyValues<R> : [never, "Error: T must be an EnumModule"] const getParserErrorMessage = <T extends RawEnum>( enumValues: EnumModule<T>["values"], enumFriendlyName: string ) => `Must be an enum value in the set ${enumFriendlyName}{ ${enumValues.join(", ")} }` const toTrimmedLowerCase = (a: string | number) => pipe( Option.some(a), Option.refine(String.isString), Option.map(flow(String.trim, String.toLowerCase)), Option.defaultValue(a) ) const isStringOrNumber = (u: NonNullish): u is string | number => typeof u === "string" || typeof u === "number" const getParseFn = <R extends RawEnum>(enumValues: EnumModule<R>["values"], enumFriendlyName: string) => (u: unknown): Result<StringKeyValues<R>, string> => pipe( Option.ofNullish(u),
Result.ofOption( () => `Enum${
enumFriendlyName ? ` ${enumFriendlyName}` : "" } cannot be null/undefined` ), Result.refine( isStringOrNumber, () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } must be a string or number` ), Result.map(toTrimmedLowerCase), Result.bind(testVal => pipe( enumValues, Array.find(val => toTrimmedLowerCase(val) === testVal), Option.match({ some: a => Result.ok(a), none: () => Result.err( getParserErrorMessage(enumValues, enumFriendlyName) ), }) ) ) ) const isFunc = (f: unknown): f is (...args: any[]) => any => typeof f === "function" const getMatchFn = <R extends RawEnum>(raw: R): EnumMatch<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (!Object.hasOwn(matcher, enumLabel)) { throw new TypeError( `Expected a matcher containing a case for '${enumLabel}'.` ) } const matcherBranch = matcher[enumLabel] return isFunc(matcherBranch) ? matcherBranch() : matcherBranch } const getMatchOrElseFn = <R extends RawEnum>(raw: R): EnumMatchOrElse<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (Object.hasOwn(matcher, enumLabel)) { const branch = matcher[enumLabel] // eslint-disable-next-line @typescript-eslint/no-unsafe-return return isFunc(branch) ? branch() : branch } return isFunc(matcher.orElse) ? matcher.orElse() : matcher.orElse } /** * Generates an "enum module" from a raw object. For motivation behind using a custom * generative function instead of the built-in `enum` types, see [this video](https://youtu.be/jjMbPt_H3RQ). * * This function augments a raw "enum object" with several useful capabilities: `values`, `parse`, `match`, * and `matchOrElse`. * - `values` contains the list of valid enum values * - `parse` is a parser funciton auto-magically created for this enum * - `match` is a pipeable function that allows exhaustive pattern matching * - `matchOrElse` is a pipeable function that allows inexhaustive pattern matching * * @remarks * You can use the `parse` function together with `io-ts` to easily create a decoder for this enum. * * @example * ```ts * export const MyEnum = enumOf({ * Dog = 'Dog', * Cat = 'Cat', * ZEBRA = 1234, * } as const, 'MyEnum') // => friendly name optional; used to generate helpful decoder errors * export type MyEnum = EnumOf<typeof MyEnum>; //=> 'Dog' | 'Cat' | 1234 * * // Standard enum-style accessors * const dog = MyEnum.Dog; // => 'Dog' * const zebra = MyEnum.ZEBRA; // => 1234 * * // Access array of all valid values, correctly typed * const myEnumValues = MyEnum.values; // => ['Dog', 'Cat', 1234] * * // Get a decoder instance for this enum automagically * const myDecoder = MyEnum.decoder; // => a `D.Decoder<unknown, 'Dog' | 'Cat' | 1234>` * * // Match an enum value against all its cases (compiler ensures exhaustiveness) * const value: MyEnum = 'Cat'; * const matchResult = pipe( * value, * MyEnum.match({ * Dog: 'woof woof', * Cat: () => 'meow', * ZEBRA: 'is my skin white with black stripes or black with white stripes??' * }) * ) // => 'meow' * ``` */ export const enumOf = <T extends RawEnum>( raw: T, enumFriendlyName = "" ): EnumModule<T> => { const entriesWithStringKeys = Object.entries(raw).reduce( (acc, [label, value]) => ({ ...acc, [label]: value, }), {} ) const values = Object.values(raw) return { ...entriesWithStringKeys, values, parse: getParseFn(values, enumFriendlyName), match: getMatchFn(raw), matchOrElse: getMatchOrElseFn(raw), } as unknown as EnumModule<T> }
src/Enums.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Nullable.ts", "retrieved_chunk": " * null,\n * Nullable.defaultWith(() => 42)\n * ) // => 42\n */\nexport const defaultWith =\n <A extends NonNullish>(f: () => A) =>\n (nullable: Nullable<A>): NonNullable<A> =>\n nullable != null ? nullable : f()\n/**\n * Similar to `Option.map`. Uses the given function to map the nullable value", "score": 0.8436017036437988 }, { "filename": "src/Option.ts", "retrieved_chunk": " * none: 0,\n * })\n * ) // => 84\n */\nexport const match =\n <A extends NonNullish, R>(matcher: OptionMatcher<A, R>) =>\n (option: Option<A>) => {\n switch (option._tag) {\n case \"Some\":\n return getMatcherResult(matcher.some, option.some)", "score": 0.8414928913116455 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": "}\nconst isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R =>\n typeof caseFn !== \"function\"\nconst getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) =>\n isRawValue(match) ? match : match(arg)\nconst objHasOptionalProp = <T extends object, P extends keyof T>(\n prop: P,\n obj: T\n): obj is Identity<T & Required<{ [key in P]: T[P] }>> => Object.hasOwn(obj, prop)\n/**", "score": 0.8403595685958862 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n */\nexport const refine = <A extends NonNullish, B extends A>(f: Refinement<A, B>) =>\n match<A, Option<B>>({\n some: a => (f(a) ? some(a) : none),\n none: none,\n })\n/**\n * Returns the wrapped value if the `Option` is `Some`,\n * otherwise uses the given value as a default value.", "score": 0.8360601663589478 }, { "filename": "src/Option.ts", "retrieved_chunk": "export const getEqualityComparer = <A extends NonNullish>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<Option<A>> =>\n // `ofEquals` has a built-in reference equality check, which captures the None/None case\n EqualityComparer.ofEquals((opt1, opt2) =>\n pipe(\n [opt1, opt2] as const,\n map2((a1: A, a2: A) => equals(a1, a2)),\n defaultValue(false)\n )", "score": 0.8354425430297852 } ]
typescript
Result.ofOption( () => `Enum${
/** * The `Deferred` type represents the state of some asynchronous operation. The * operation can either be `NotStarted`, `InProgress`, or `Resolved`. When the * operation is resolved, it has some data attached to it that represents the * outcome of the asyncrhonous work. * * This type is frequently used with `Result` as the data of the `Resolved` * branch, because it is a common situation to model the outcome of an asynchronous * operation that can fail. * * This type is especially helpful in Redux stores (or in the React `useReducer` * state) because it allows you to determinstically model the state of an async * operation as one value. I.e., instead of using separate flags that are * _implicitly_ related to each other (e.g., `notStarted`, `loading`, `result`), * you know for a fact that the async work can only be in one of three states, * and the data present on the resolved state is _only_ present on the resolved * state. * * @example * declare const def: Deferred<ApiResponse> * * pipe( * def, * Deferred.match({ * notStarted: "Not Started", * inProgress: "In Progress", * resolved: response => response.body * }) * ) * * @module Deferred */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive } from "./prelude" import { pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" /** The `NotStarted` type. */ export interface NotStarted extends Tagged<"NotStarted", object> {} /** The `InProgress` type. */ export interface InProgress extends Tagged<"InProgress", object> {} /** The `Resolved` type. */ export interface Resolved<A> extends Tagged<"Resolved", { resolved: A }> {} /** A discriminated union type representing a `Deferred` value. */ export type Deferred<A> = NotStarted | InProgress | Resolved<A> /** * The static `NotStarted` instance. * * @group Constructors */ export const notStarted: Deferred<never> = Object.freeze({ _tag: "NotStarted" }) /** * The static `InProgress` instance. * * @group Constructors */ export const inProgress: Deferred<never> = Object.freeze({ _tag: "InProgress" }) /** * Construct a new `Resolved` instance with the given data attached. * * @param a The data that will be wrapped in the `Deferred`. * * @group Constructors */ export const resolved = <A>(a: A): Deferred<A> => ({ _tag: "Resolved", resolved: a }) /** @ignore */ interface DeferredMatcher<A, R> { readonly notStarted: (() => R) | R readonly inProgress: (() => R) | R readonly resolved: ((a: A) => R) | R } /** @ignore */ interface PartialDeferredMatcher<A, R> extends Partial<DeferredMatcher<A, R>> { readonly orElse: (() => R) | R } type Func<T> = (...args: any[]) => T type FuncOrValue<T> = Func<T> | T const resultOrValue = <T>(f: FuncOrValue<T>, ...args: any[]) => { const isFunc = (f: FuncOrValue<T>): f is Func<T> => typeof f === "function" // eslint-disable-next-line @typescript-eslint/no-unsafe-argument return isFunc(f) ? f(...args) : f } /** * Exhaustively pattern match against a `Deferred` value. Provide either * a value or a lambda to use for each case. If you provide a lambda to the * `resolved` case, it will be given the data associated with the `Resolved` * instance. * * See docs for {@link Deferred} for example. * * @param matcher The matcher object to use. * * @group Pattern Matching * * @example * ``` * declare const def: Deferred<MyApiResponse> * pipe( * def, * Deferred.match({ * notStarted: "", * inProgress: "Loading...", * resolved: resp => resp?.body ?? "" * }) * ) // => the string produced in each case, depending on the value of `def` * ``` */ export const match = <A, R>(matcher: DeferredMatcher<A, R>) => (deferred: Deferred<A>) => { switch (deferred._tag) { case "NotStarted": return resultOrValue(matcher.notStarted) case "InProgress": return resultOrValue(matcher.inProgress) case "Resolved": return resultOrValue(matcher.resolved, deferred.resolved) /* c8 ignore next 2 */ default: return assertExhaustive(deferred) as R } } /** * Non-exhaustive pattern match against a `Deferred`. Provide a lambda or raw value * to return for the various cases. (But don't specify all the cases. You should use * {@link match} if you want exhaustive case checking.) Then also provide a raw value * or lambda to use for the `orElse` case if the check falls through all other cases. * * @group Pattern Matching * * @example * ``` * declare const def: Deferred<number> * pipe( * def, * Deferred.matchOrElse({ * resolved: statusCode => `Status: ${statusCode}`, * orElse: 'Not Finished' // effectively captures both "in progress" and "not started" cases together * }) * ) * ``` */ export const matchOrElse = <A, R>(matcher: PartialDeferredMatcher<A, R>) => (deferred: Deferred<A>) => { switch (deferred._tag) { case "NotStarted": return resultOrValue( matcher.notStarted != null ? matcher.notStarted : matcher.orElse ) case "InProgress": return resultOrValue( matcher.inProgress != null ? matcher.inProgress : matcher.orElse ) case "Resolved": return matcher.resolved != null ? resultOrValue(matcher.resolved, deferred.resolved) : resultOrValue(matcher.orElse) /* c8 ignore next 2 */ default: return resultOrValue(matcher.orElse) } } /** * Get whether the `Deferred` is either in progress or not started. * * @group Utils */ export const isUnresolved: <A>(deferred: Deferred<A>) => boolean = matchOrElse({ resolved: false, orElse: true, }) /** * Gets whether the `Deferred` is in progress. * * @group Utils */ export const isInProgress = <A>(deferred: Deferred<A>): deferred is InProgress => pipe( deferred, matchOrElse({ inProgress: true, orElse: false, }) ) /** * Gets whether the `Deferred` is resolved. * * @group Utils */ export const isResolved = <A>(deferred: Deferred<A>): deferred is Resolved<A> => pipe( deferred, matchOrElse({ resolved: true, orElse: false, }) ) /** * Gets whether the `Deferred` is resolved with data equal to a specific value. * Uses the `EqualityComparer` if given, otherwise defaults to reference (triple * equals) equality. * * @group Pattern Matching * @group Utils * * @example * pipe( * Deferred.resolved(101), * Deferred.isResolvedWith(100, EqualityComparer.Number) * // number is just a trivial example here, not required * ) // => false */ export const isResolvedWith = <A>( expected: A,
equalityComparer: EqualityComparer<A> = EqualityComparer.Default ) => matchOrElse<A, boolean>({
resolved: actual => equalityComparer.equals(actual, expected), orElse: false, }) /* c8 ignore start */ /** @ignore */ export const Deferred = { notStarted, inProgress, resolved, match, matchOrElse, isUnresolved, isResolved, isInProgress, isResolvedWith, } /* c8 ignore end */
src/Deferred.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Nullable.ts", "retrieved_chunk": " * equals(4, 4) // => true\n * equals(4, 5) // => false\n * ```\n */\nexport const getEqualityComparer = <A extends NonNullish>(\n equalityComparer: EqualityComparer<A>\n) =>\n EqualityComparer.ofEquals<Nullable<A>>(\n (a1, a2) =>\n (a1 == null && a2 == null) ||", "score": 0.8625224828720093 }, { "filename": "src/Option.ts", "retrieved_chunk": " * Option.bind(mightFailB), // Option<number>\n * Option.defaultWith(() => 0) // number\n * )\n * // => 200 if both mightFail functions return `Some`\n * // => 0 if either function returns `None`\n * ```\n */\nexport const bind = <A extends NonNullish, B extends NonNullish>(\n f: (a: A) => Option<B>\n) =>", "score": 0.8556575775146484 }, { "filename": "src/Option.ts", "retrieved_chunk": " * ```\n */\nexport const refine = <A extends NonNullish, B extends A>(f: Refinement<A, B>) =>\n match<A, Option<B>>({\n some: a => (f(a) ? some(a) : none),\n none: none,\n })\n/**\n * Returns the wrapped value if the `Option` is `Some`,\n * otherwise uses the given value as a default value.", "score": 0.8537711501121521 }, { "filename": "src/Option.ts", "retrieved_chunk": " * none: 0,\n * })\n * ) // => 84\n */\nexport const match =\n <A extends NonNullish, R>(matcher: OptionMatcher<A, R>) =>\n (option: Option<A>) => {\n switch (option._tag) {\n case \"Some\":\n return getMatcherResult(matcher.some, option.some)", "score": 0.8528555631637573 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " * resolvedErr: apiError => `Error was: ${ApiError.toString(apiError)}`\n * })\n * )\n * ```\n */\nexport const match =\n <A, E, R>(matcher: DeferredResultMatcher<A, E, R>) =>\n (deferredResult: DeferredResult<A, E>) => {\n switch (deferredResult._tag) {\n case \"InProgress\":", "score": 0.846875011920929 } ]
typescript
equalityComparer: EqualityComparer<A> = EqualityComparer.Default ) => matchOrElse<A, boolean>({
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer"
export interface Ok<A> extends Tagged<"Ok", { ok: A }> {}
export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else if (isErr(results[1])) { return err(results[1].err) } else { return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => { if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Option.ts", "retrieved_chunk": " * console.info\n * ) // logs \"56!\"\n * ```\n *\n * @module Option\n */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { Tagged, assertExhaustive, Refinement, NonNullish } from \"./prelude\"\nimport { pipe } from \"./Composition\"\nimport { EqualityComparer } from \"./EqualityComparer\"", "score": 0.931321382522583 }, { "filename": "src/Deferred.ts", "retrieved_chunk": " * @module Deferred\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { Tagged, assertExhaustive } from \"./prelude\"\nimport { pipe } from \"./Composition\"\nimport { EqualityComparer } from \"./EqualityComparer\"\n/** The `NotStarted` type. */\nexport interface NotStarted extends Tagged<\"NotStarted\", object> {}\n/** The `InProgress` type. */", "score": 0.8796248435974121 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " * See docs for {@link match} and {@link matchOrElse} for code examples.\n *\n * @module\n */\nimport { pipe } from \"./Composition\"\nimport { Deferred } from \"./Deferred\"\nimport { assertExhaustive, Identity } from \"./prelude\"\nimport { Result } from \"./Result\"\nexport type DeferredResult<A, E> = Deferred<Result<A, E>>\n/** @ignore */", "score": 0.8561474680900574 }, { "filename": "src/Map.ts", "retrieved_chunk": "/**\n * A suite of useful functions for working with the built-in `Map` type.\n *\n * @module Map\n */\nimport { NonNullish, Predicate } from \"./prelude\"\nimport { Option } from \"./Option\"\nimport { pipe } from \"./Composition\"\nimport { EqualityComparer } from \"./EqualityComparer\"\nimport { OrderingComparer } from \"./OrderingComparer\"", "score": 0.8552118539810181 }, { "filename": "src/index.ts", "retrieved_chunk": "export { pipe, flow } from \"./Composition\"\nexport { tee, teeAsync } from \"./function\"\nexport { String } from \"./string\"\nexport { EqualityComparer } from \"./EqualityComparer\"\nexport { OrderingComparer } from \"./OrderingComparer\"\nexport { Nullable } from \"./Nullable\"\nexport { Option } from \"./Option\"\nexport { Result } from \"./Result\"\nexport { Async } from \"./Async\"\nexport { AsyncResult } from \"./AsyncResult\"", "score": 0.8353443145751953 } ]
typescript
export interface Ok<A> extends Tagged<"Ok", { ok: A }> {}
/** * A `NonEmptyArray` is an array that is guaranteed by the type system to have * at least one element. This type is useful for correctly modeling certain * behaviors where empty arrays are absurd. It also makes it safer to work with * functionality like destructuring the array or getting the first value. * * **Note:** A `NonEmptyArray` is just a _more specific_ type of readonly array, * so any functions from the `Array` module can also be used with `NonEmptyArray`s. * * @module NonEmptyArray */ import { EqualityComparer } from "./EqualityComparer" import { OrderingComparer } from "./OrderingComparer" /** Represents a readonly array with at least one element. */ export interface NonEmptyArray<A> extends ReadonlyArray<A> { 0: A } /** * Get the first element of a non-empty array. * * @group Utils * @group Pattern Matching */ export const head = <A>(as: NonEmptyArray<A>) => as[0] /** * Alias of {@link head}. * * @group Pattern Matching * @group Utils */ export const first = head /** * Destructure the non-empty array into an object containing * the head and the tail. * * @group Pattern Matching * * @example * NonEmptyArray.destruct([1, 2, 3]) // => { head: 1, tail: [2, 3] } */ export const destruct = <A>( as: NonEmptyArray<A> ): { readonly head: A readonly tail: readonly A[] } => ({ head: as[0], tail: as.slice(1), }) /** * Curried version of the built-in map that maintains * strong NonEmptyArray typing. * * @group Mapping * * @returns A new non-empty array containing the mapped elements. */ export const map = <A, B>(f: (a: A) => B) => (as: NonEmptyArray<A>): NonEmptyArray<B> => as.map(f) as unknown as NonEmptyArray<B> /** * Uses the given function to map each element into a non-empty array, * then flattens the results. Commonly called flatMap` or `chain`. * * @group Mapping * * @returns A new non-empty array containing the mapped/flattened elements. */ export const bind = <A, B>(f: (a: A) => NonEmptyArray<B>) => (as: NonEmptyArray<A>): NonEmptyArray<B> => as.flatMap(f) as unknown as NonEmptyArray<B> /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * Constructs a new non-empty array containing exactly one element. * * @group Constructors */ export const of = <A>(a: A): NonEmptyArray<A> => [a] /** * Create a new array by enumerating the integers between * the given start and end, inclusive of both start and end. * * Both start and end are normalized to integers, and end is * normalized to always be at least equal to start. * * @group Constructors * @group Utils * * @example * NonEmptyArray.range(1, 5) // => [1, 2, 3, 4, 5] * NonEmptyArray.range(-10, 1) // => [-10, -9, -8, ..., 1] * NonEmptyArray.range(2, -5) // => [2] * NonEmptyArray.range(1, 1) // => [1] */ export const range = ( startInclusive: number, endInclusive: number ): NonEmptyArray<number> => { const start = Math.floor(startInclusive) const end = Math.floor(endInclusive) if (start >= end) { return [start] } const out: number[] = [] for (let i = start; i <= end; i++) { out.push(i) } return out as unknown as NonEmptyArray<number> } /** * Construct a new non-empty array with the specified number * of elements, using a constructor function for each element * that takes a zero-based index of the element being constructed. * * @param length is normalized to a non-negative integer * * @group Constructors * @group Utils * * @example * ``` * NonEmptyArray.make(3, i => `${i}`) // => ["0", "1", "2"] * ``` */ export const make = <A>( length: number, createElement: (i: number) => A ): NonEmptyArray<A> => { const n = length <= 1 ? 1 : Math.floor(length) return [...Array(n).keys()].map(createElement) as unknown as NonEmptyArray<A> } /** * Reverses an array. Preserves correct types. * * @group Utils * * @returns A new non-empty array with elements in reverse order. * * @example * pipe( * NonEmptyArray.range(1, 5), * NonEmptyArray.reverse * ) // => [5, 4, 3, 2, 1] */ export const reverse = <A>(as: NonEmptyArray<A>): NonEmptyArray<A> => as.slice(0).reverse() as unknown as NonEmptyArray<A> /** * Sort the array using the given `OrderingComaparer`, or the default * ASCII-based comparer if not given. * * @group Utils * * @returns A new non-emty array with elements sorted. */ export const sort = <A>(orderingComparer: OrderingComparer<A> = OrderingComparer.Default) => (as: NonEmptyArray<A>): NonEmptyArray<A> => as.slice(0).sort(orderingComparer.compare) as unknown as NonEmptyArray<A> /** * Get an `EqualityComparer` that represents structural equality for a non-empty array * of type `A` by giving this function an `EqualityComparer` for each `A` element. * * @group Equality * @group Utils * * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A>({ equals, }:
EqualityComparer<A>): EqualityComparer<NonEmptyArray<A>> => EqualityComparer.ofEquals((arr1, arr2) => {
if (arr1.length !== arr2.length) { return false } for (let i = 0; i < arr1.length; i++) { if (!equals(arr1[i], arr2[i])) { return false } } return true }) /* c8 ignore start */ /** @ignore */ export const NonEmptyArray = { head, first, destruct, map, bind, flatMap, of, range, make, reverse, sort, getEqualityComparer, } /* c8 ignore end */
src/NonEmptyArray.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Result.ts", "retrieved_chunk": " * @group Utils\n *\n * @param equalityComparerA The `EqualityComparer` to use for the inner ok value.\n * @param equalityComparerE The `EqualityComparer` to use for the inner err value.\n *\n * @returns A new `EqualityComparer` instance\n */\nexport const getEqualityComparer = <A, E>(\n equalityComparerA: EqualityComparer<A>,\n equalityComparerE: EqualityComparer<E>", "score": 0.9126297235488892 }, { "filename": "src/OrderingComparer.ts", "retrieved_chunk": " * that is compatible with `Ord` from `fp-ts`.\n *\n * @returns A new instance that implements both `EqualityComparer` and `OrderingComparer`\n *\n * @group Utils\n */\nexport const deriveEqualityComparer = <A>(\n orderingComparer: OrderingComparer<A>\n): OrderingComparer<A> & EqualityComparer<A> => ({\n compare: orderingComparer.compare,", "score": 0.910773754119873 }, { "filename": "src/EqualityComparer.ts", "retrieved_chunk": " }\n return true\n })\n/**\n * The default `EqualityComparer`, which uses reference (triple equals) equality.\n *\n * @group Primitives\n */\nexport const Default: EqualityComparer<never> = Object.freeze(\n ofEquals((a1, a2) => a1 === a2)", "score": 0.8971468210220337 }, { "filename": "src/Nullable.ts", "retrieved_chunk": " * equals(4, 4) // => true\n * equals(4, 5) // => false\n * ```\n */\nexport const getEqualityComparer = <A extends NonNullish>(\n equalityComparer: EqualityComparer<A>\n) =>\n EqualityComparer.ofEquals<Nullable<A>>(\n (a1, a2) =>\n (a1 == null && a2 == null) ||", "score": 0.8953597545623779 }, { "filename": "src/Array.ts", "retrieved_chunk": " * const eq = Array.getEqualityComparer(EqualityComparer.Number)\n * eq.equals([1, 2, 3], [1, 2, 3]) // => true\n * eq.equals([1, 3], [3, 1]) // => false\n */\nexport const getEqualityComparer = <A>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<readonly A[]> =>\n EqualityComparer.ofEquals((arr1, arr2) => {\n if (isEmpty(arr1) && isEmpty(arr2)) {\n return true", "score": 0.8806784749031067 } ]
typescript
EqualityComparer<A>): EqualityComparer<NonEmptyArray<A>> => EqualityComparer.ofEquals((arr1, arr2) => {
/** * The `Deferred` type represents the state of some asynchronous operation. The * operation can either be `NotStarted`, `InProgress`, or `Resolved`. When the * operation is resolved, it has some data attached to it that represents the * outcome of the asyncrhonous work. * * This type is frequently used with `Result` as the data of the `Resolved` * branch, because it is a common situation to model the outcome of an asynchronous * operation that can fail. * * This type is especially helpful in Redux stores (or in the React `useReducer` * state) because it allows you to determinstically model the state of an async * operation as one value. I.e., instead of using separate flags that are * _implicitly_ related to each other (e.g., `notStarted`, `loading`, `result`), * you know for a fact that the async work can only be in one of three states, * and the data present on the resolved state is _only_ present on the resolved * state. * * @example * declare const def: Deferred<ApiResponse> * * pipe( * def, * Deferred.match({ * notStarted: "Not Started", * inProgress: "In Progress", * resolved: response => response.body * }) * ) * * @module Deferred */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive } from "./prelude" import { pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" /** The `NotStarted` type. */ export interface NotStarted extends Tagged<"NotStarted", object> {} /** The `InProgress` type. */ export interface InProgress extends Tagged<"InProgress", object> {} /** The `Resolved` type. */ export interface Resolved<A> extends Tagged<"Resolved", { resolved: A }> {} /** A discriminated union type representing a `Deferred` value. */ export type Deferred<A> = NotStarted | InProgress | Resolved<A> /** * The static `NotStarted` instance. * * @group Constructors */ export const notStarted: Deferred<never> = Object.freeze({ _tag: "NotStarted" }) /** * The static `InProgress` instance. * * @group Constructors */ export const inProgress: Deferred<never> = Object.freeze({ _tag: "InProgress" }) /** * Construct a new `Resolved` instance with the given data attached. * * @param a The data that will be wrapped in the `Deferred`. * * @group Constructors */ export const resolved = <A>(a: A): Deferred<A> => ({ _tag: "Resolved", resolved: a }) /** @ignore */ interface DeferredMatcher<A, R> { readonly notStarted: (() => R) | R readonly inProgress: (() => R) | R readonly resolved: ((a: A) => R) | R } /** @ignore */ interface PartialDeferredMatcher<A, R> extends Partial<DeferredMatcher<A, R>> { readonly orElse: (() => R) | R } type Func<T> = (...args: any[]) => T type FuncOrValue<T> = Func<T> | T const resultOrValue = <T>(f: FuncOrValue<T>, ...args: any[]) => { const isFunc = (f: FuncOrValue<T>): f is Func<T> => typeof f === "function" // eslint-disable-next-line @typescript-eslint/no-unsafe-argument return isFunc(f) ? f(...args) : f } /** * Exhaustively pattern match against a `Deferred` value. Provide either * a value or a lambda to use for each case. If you provide a lambda to the * `resolved` case, it will be given the data associated with the `Resolved` * instance. * * See docs for {@link Deferred} for example. * * @param matcher The matcher object to use. * * @group Pattern Matching * * @example * ``` * declare const def: Deferred<MyApiResponse> * pipe( * def, * Deferred.match({ * notStarted: "", * inProgress: "Loading...", * resolved: resp => resp?.body ?? "" * }) * ) // => the string produced in each case, depending on the value of `def` * ``` */ export const match = <A, R>(matcher: DeferredMatcher<A, R>) => (deferred: Deferred<A>) => { switch (deferred._tag) { case "NotStarted": return resultOrValue(matcher.notStarted) case "InProgress": return resultOrValue(matcher.inProgress) case "Resolved": return resultOrValue(matcher.resolved, deferred.resolved) /* c8 ignore next 2 */ default: return
assertExhaustive(deferred) as R }
} /** * Non-exhaustive pattern match against a `Deferred`. Provide a lambda or raw value * to return for the various cases. (But don't specify all the cases. You should use * {@link match} if you want exhaustive case checking.) Then also provide a raw value * or lambda to use for the `orElse` case if the check falls through all other cases. * * @group Pattern Matching * * @example * ``` * declare const def: Deferred<number> * pipe( * def, * Deferred.matchOrElse({ * resolved: statusCode => `Status: ${statusCode}`, * orElse: 'Not Finished' // effectively captures both "in progress" and "not started" cases together * }) * ) * ``` */ export const matchOrElse = <A, R>(matcher: PartialDeferredMatcher<A, R>) => (deferred: Deferred<A>) => { switch (deferred._tag) { case "NotStarted": return resultOrValue( matcher.notStarted != null ? matcher.notStarted : matcher.orElse ) case "InProgress": return resultOrValue( matcher.inProgress != null ? matcher.inProgress : matcher.orElse ) case "Resolved": return matcher.resolved != null ? resultOrValue(matcher.resolved, deferred.resolved) : resultOrValue(matcher.orElse) /* c8 ignore next 2 */ default: return resultOrValue(matcher.orElse) } } /** * Get whether the `Deferred` is either in progress or not started. * * @group Utils */ export const isUnresolved: <A>(deferred: Deferred<A>) => boolean = matchOrElse({ resolved: false, orElse: true, }) /** * Gets whether the `Deferred` is in progress. * * @group Utils */ export const isInProgress = <A>(deferred: Deferred<A>): deferred is InProgress => pipe( deferred, matchOrElse({ inProgress: true, orElse: false, }) ) /** * Gets whether the `Deferred` is resolved. * * @group Utils */ export const isResolved = <A>(deferred: Deferred<A>): deferred is Resolved<A> => pipe( deferred, matchOrElse({ resolved: true, orElse: false, }) ) /** * Gets whether the `Deferred` is resolved with data equal to a specific value. * Uses the `EqualityComparer` if given, otherwise defaults to reference (triple * equals) equality. * * @group Pattern Matching * @group Utils * * @example * pipe( * Deferred.resolved(101), * Deferred.isResolvedWith(100, EqualityComparer.Number) * // number is just a trivial example here, not required * ) // => false */ export const isResolvedWith = <A>( expected: A, equalityComparer: EqualityComparer<A> = EqualityComparer.Default ) => matchOrElse<A, boolean>({ resolved: actual => equalityComparer.equals(actual, expected), orElse: false, }) /* c8 ignore start */ /** @ignore */ export const Deferred = { notStarted, inProgress, resolved, match, matchOrElse, isUnresolved, isResolved, isInProgress, isResolvedWith, } /* c8 ignore end */
src/Deferred.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/DeferredResult.ts", "retrieved_chunk": " return getMatcherResult(matcher.inProgress, undefined)\n case \"NotStarted\":\n return getMatcherResult(matcher.notStarted, undefined)\n case \"Resolved\":\n return pipe(\n deferredResult.resolved,\n Result.match({\n ok: a => getMatcherResult(matcher.resolvedOk, a),\n err: e => getMatcherResult(matcher.resolvedErr, e),\n })", "score": 0.868739128112793 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " ? getMatcherResult(matcher.inProgress, undefined)\n : getMatcherResult(matcher.orElse, undefined)\n case \"NotStarted\":\n return objHasOptionalProp(\"notStarted\", matcher)\n ? getMatcherResult(matcher.notStarted, undefined)\n : getMatcherResult(matcher.orElse, undefined)\n case \"Resolved\":\n return pipe(\n deferredResult.resolved,\n Result.match({", "score": 0.8590927720069885 }, { "filename": "src/Result.ts", "retrieved_chunk": " case \"Ok\":\n return getMatcherResult(matcher.ok, result.ok)\n case \"Err\":\n return getMatcherResult(matcher.err, result.err)\n /* c8 ignore next 2 */\n default:\n return assertExhaustive(result)\n }\n }\n/**", "score": 0.8491547107696533 }, { "filename": "src/Option.ts", "retrieved_chunk": " case \"None\":\n return getMatcherResult(matcher.none, void 0)\n /* c8 ignore next 2 */\n default:\n return assertExhaustive(option)\n }\n }\n/**\n * Maps the wrapped `Some` value using the given function.\n * Passes through `None` as-is.", "score": 0.82382732629776 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " * })\n * )\n * ```\n */\nexport const matchOrElse =\n <A, E, R>(matcher: PartialDeferredResultMatcher<A, E, R>) =>\n (deferredResult: DeferredResult<A, E>) => {\n switch (deferredResult._tag) {\n case \"InProgress\":\n return objHasOptionalProp(\"inProgress\", matcher)", "score": 0.8205070495605469 } ]
typescript
assertExhaustive(deferred) as R }
/** See [Enums considered harmful](https://www.youtube.com/watch?v=jjMbPt_H3RQ) for the motivation behind this custom type. (Also worth noting is that in TypeScript 5.0 [all Enums are considered unions](https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#all-enums-are-union-enums).) Similar to [variants](variants.md) for disciminated unions, `enumOf` allows you to more easily and safely create and work with enums in TypeScript. ## Basic Example ```ts export const MyEnum = enumOf( { Dog = "Dog", Cat = "Cat", ZEBRA = 1234, } as const, // the `as const` won't be required in TypeScript 5.0 "MyEnum" // friendly name is optional; used to generate helpful parser errors ) export type MyEnum = EnumOf<typeof MyEnum> // => "Dog" | "Cat" | 1234 ``` ## Methods ### Standard enum-style accessors ```ts const dog = MyEnum.Dog // => "Dog" const zebra = MyEnum.ZEBRA // => 1234 ``` ### Values Access array of all valid values, correctly typed (but without any ordering guarantees). ```ts const myEnumValues = MyEnum.values // => ["Dog", "Cat", 1234] ``` ### Parser Get a safe parser function for this enum automagically! ```ts const parsed = MyEnum.parse("cat") // => a `Result<MyEnum, string>`, in this case `Result.ok("Cat")` ``` ### Match See `match` in the {@link Variants} module docs for more details on matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.match({ Dog: "woof woof", Cat: () => "meow", ZEBRA: "is my skin white with black stripes or black with white stripes??", }) speak(myEnum) ``` ### MatchOrElse See `matchOrElse` in the {@link Variants} module docs for more details on partial matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.matchOrElse({ Dog: "woof woof", Cat: () => "meow", orELse: "I cannot speak.", }) speak(myEnum) ``` @module Enums */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Result } from "./Result" import { String } from "./string" import { Option } from "./Option" import { pipe, flow } from "./Composition" import { Array } from "./Array" import { Identity, NonNullish } from "./prelude" /** @ignore */ type StringKeys<T extends object> = Extract<keyof T, string> /** * A plain object that serves as the definition of the enum type. * Until TypeScript 5.0 is released, you need to specify `as const` * on this object definition. */ type RawEnum = Record<string, string | number> /** @ignore */ type StringKeyValues<T extends
RawEnum> = Identity<T[StringKeys<T>]> /** @ignore */ type EnumMatcher<A, R extends RawEnum> = {
readonly [Label in StringKeys<R>]: (() => A) | A } /** @ignore */ type PartialEnumMatcher<A, R extends RawEnum> = Partial<EnumMatcher<A, R>> & { readonly orElse: (() => A) | A } type EnumMatch<R extends RawEnum> = <A>( matcher: EnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A type EnumMatchOrElse<R extends RawEnum> = <A>( matcher: PartialEnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A /** * The output of the {@link enumOf} function. Produces an object that serves both as * the enum as well as a namespace for helper functions related to that enum. */ type EnumModule<R extends RawEnum> = Identity< { readonly [Label in StringKeys<R>]: R[Label] } & { /** * Returns a readonly array containing the set of all possible enum values. No * guarantees are made regarding the order of items in the resultant array. */ readonly values: ReadonlyArray<StringKeyValues<R>> /** * For string enum values, the parse function will trim and coerce values to lowercase * before comparison. (This has no effect on numeric enum values.) Thus, if an * enum is defined as `'Yes' | 'No'`, this decoder will parse `'yes'`, `' yES'`, * and `' YES '` correctly into the canonical `'Yes'` enum value. */ readonly parse: (u: unknown) => Result<StringKeyValues<R>, string> /** * Use this function for an exhaustive case check that doesn't require using * a switch/case block or any kind of assertExhaustive check. */ readonly match: EnumMatch<R> /** * Use this function for a partial case check that doesn't require using * a switch/case block. */ readonly matchOrElse: EnumMatchOrElse<R> } > /** * Gets the union type representing all possible enum values. */ export type EnumOf<T> = T extends EnumModule<infer R> ? StringKeyValues<R> : [never, "Error: T must be an EnumModule"] const getParserErrorMessage = <T extends RawEnum>( enumValues: EnumModule<T>["values"], enumFriendlyName: string ) => `Must be an enum value in the set ${enumFriendlyName}{ ${enumValues.join(", ")} }` const toTrimmedLowerCase = (a: string | number) => pipe( Option.some(a), Option.refine(String.isString), Option.map(flow(String.trim, String.toLowerCase)), Option.defaultValue(a) ) const isStringOrNumber = (u: NonNullish): u is string | number => typeof u === "string" || typeof u === "number" const getParseFn = <R extends RawEnum>(enumValues: EnumModule<R>["values"], enumFriendlyName: string) => (u: unknown): Result<StringKeyValues<R>, string> => pipe( Option.ofNullish(u), Result.ofOption( () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } cannot be null/undefined` ), Result.refine( isStringOrNumber, () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } must be a string or number` ), Result.map(toTrimmedLowerCase), Result.bind(testVal => pipe( enumValues, Array.find(val => toTrimmedLowerCase(val) === testVal), Option.match({ some: a => Result.ok(a), none: () => Result.err( getParserErrorMessage(enumValues, enumFriendlyName) ), }) ) ) ) const isFunc = (f: unknown): f is (...args: any[]) => any => typeof f === "function" const getMatchFn = <R extends RawEnum>(raw: R): EnumMatch<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (!Object.hasOwn(matcher, enumLabel)) { throw new TypeError( `Expected a matcher containing a case for '${enumLabel}'.` ) } const matcherBranch = matcher[enumLabel] return isFunc(matcherBranch) ? matcherBranch() : matcherBranch } const getMatchOrElseFn = <R extends RawEnum>(raw: R): EnumMatchOrElse<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (Object.hasOwn(matcher, enumLabel)) { const branch = matcher[enumLabel] // eslint-disable-next-line @typescript-eslint/no-unsafe-return return isFunc(branch) ? branch() : branch } return isFunc(matcher.orElse) ? matcher.orElse() : matcher.orElse } /** * Generates an "enum module" from a raw object. For motivation behind using a custom * generative function instead of the built-in `enum` types, see [this video](https://youtu.be/jjMbPt_H3RQ). * * This function augments a raw "enum object" with several useful capabilities: `values`, `parse`, `match`, * and `matchOrElse`. * - `values` contains the list of valid enum values * - `parse` is a parser funciton auto-magically created for this enum * - `match` is a pipeable function that allows exhaustive pattern matching * - `matchOrElse` is a pipeable function that allows inexhaustive pattern matching * * @remarks * You can use the `parse` function together with `io-ts` to easily create a decoder for this enum. * * @example * ```ts * export const MyEnum = enumOf({ * Dog = 'Dog', * Cat = 'Cat', * ZEBRA = 1234, * } as const, 'MyEnum') // => friendly name optional; used to generate helpful decoder errors * export type MyEnum = EnumOf<typeof MyEnum>; //=> 'Dog' | 'Cat' | 1234 * * // Standard enum-style accessors * const dog = MyEnum.Dog; // => 'Dog' * const zebra = MyEnum.ZEBRA; // => 1234 * * // Access array of all valid values, correctly typed * const myEnumValues = MyEnum.values; // => ['Dog', 'Cat', 1234] * * // Get a decoder instance for this enum automagically * const myDecoder = MyEnum.decoder; // => a `D.Decoder<unknown, 'Dog' | 'Cat' | 1234>` * * // Match an enum value against all its cases (compiler ensures exhaustiveness) * const value: MyEnum = 'Cat'; * const matchResult = pipe( * value, * MyEnum.match({ * Dog: 'woof woof', * Cat: () => 'meow', * ZEBRA: 'is my skin white with black stripes or black with white stripes??' * }) * ) // => 'meow' * ``` */ export const enumOf = <T extends RawEnum>( raw: T, enumFriendlyName = "" ): EnumModule<T> => { const entriesWithStringKeys = Object.entries(raw).reduce( (acc, [label, value]) => ({ ...acc, [label]: value, }), {} ) const values = Object.values(raw) return { ...entriesWithStringKeys, values, parse: getParseFn(values, enumFriendlyName), match: getMatchFn(raw), matchOrElse: getMatchOrElseFn(raw), } as unknown as EnumModule<T> }
src/Enums.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/prelude.ts", "retrieved_chunk": "/* c8 ignore end */\n/**\n * Internal utility type to get slight improvements in\n * intellisense for complex TypeScript object types.\n *\n * @ignore\n */\nexport type Identity<T> = T extends object\n ? NonNullish & {\n [P in keyof T]: T[P]", "score": 0.864147424697876 }, { "filename": "src/Array.ts", "retrieved_chunk": " * Type guard that tests whether the given array is equivalent\n * to the empty tuple type.\n *\n * @group Type Guards\n * @group Utils\n */\nexport const isEmpty = <A>(as: readonly A[]): as is readonly [] => as.length === 0\n/**\n * Type guard that tests whether the given array is a `NonEmptyArray`\n *", "score": 0.8532537817955017 }, { "filename": "src/Result.ts", "retrieved_chunk": " */\nexport const flatMap = bind\n/**\n * A type guard (a.k.a. `Refinement`) that holds if the result\n * is an `Ok`. Allows the TypeScript compiler to narrow the type\n * and allow type-safe access to `.ok`.\n *\n * @group Type Guards\n */\nexport const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> =>", "score": 0.8512274622917175 }, { "filename": "src/Nullable.ts", "retrieved_chunk": " * Similar to `Option.bind`. Maps the nullable value using a function that itself\n * returns a possibly nullish value, and flattens the result.\n *\n * @group Mapping\n *\n * @example\n * ```\n * type Person = { readonly name?: string }\n *\n * declare const person: Nullable<Person>", "score": 0.8482452630996704 }, { "filename": "src/prelude.ts", "retrieved_chunk": " }\n : T\n/**\n * Internal utility type for discriminated unions.\n *\n * @ignore\n */\nexport type Tagged<Tag extends string, A extends object> = Identity<\n Readonly<\n {", "score": 0.8443228006362915 } ]
typescript
RawEnum> = Identity<T[StringKeys<T>]> /** @ignore */ type EnumMatcher<A, R extends RawEnum> = {
/** * An `OrderingComparer` represents the ability to deterministcally sort a set of values. * Meaning, it should always give back the same sort order given the same set of values. * * The `compare` function returns `-1` if the first item is _less than_ the second * item. It returns `1` if the first item is _greater than_ the second item in the * sort order. It returns `0` if the first item is equivalent to the second item * with reference to the sort order. * * **Note:** An `OrderingComparer` is not structurally compatible with an `Ord` from `fp-ts` * by default. You can get an `Ord`-compatible structure via {@link deriveEqualityComparer}. * * @example * interface Pet { * readonly name: string * readonly age: number * } * * class PetByAgeDescComparer implements OrderingComparer<Pet> { * compare(p1: Pet, p2: Pet) { * return p1.age === p2.age ? 0 : p1.age < p2.age ? 1 : -1 * } * } * * @module OrderingComparer */ import { String as S } from "./string" import { EqualityComparer } from "./EqualityComparer" /** * A more strict version of the default JavaScript compare function result. * (i.e., `-1` and `1` are required specifically, not just `< 0` or `> 0`) */ type CompareResult = | -1 // the first value is considered _less than_ the second value | 0 // the first value is considered _the same as_ the second value | 1 // the first value is considered _greater than_ the second value export interface OrderingComparer<A> { compare(a1: A, a2: A): CompareResult } /** * Construct a new `OrderingComparer` based on a compare function that returns * `-1`, `0`, or `1`. See docs for {@link OrderingComparer}. * * **Note:** this function already checks for reference equality and will return * `0` in that case. (So the compare function you pass here does not necessarily * need to check for reference equality.) * * @group Constructors * * @returns A new `OrderingComparer` instance. */ export const ofCompare = <A>( compare: OrderingComparer<A>["compare"] ): OrderingComparer<A> => ({ compare: (a1, a2) => (a1 === a2 ? 0 : compare(a1, a2)), }) /** * Reverse the sort order produced by an `OrderingComparer`. For example, you could use this * to generate an `OrderingComparer` that would sort numbers in descending order. * * @group Utils * * @returns A new `OrderingComparer` with its sort order inverted. * * @example * const numberDesc = OrderingComparer.reverse(OrderingComparer.Number) */ export const reverse = <A>({ compare }: OrderingComparer<A>): OrderingComparer<A> => ofCompare((a1, a2) => compare(a2, a1)) /** * Given you already have an `OrderingComparer` for some type `A`, and you know how to * map from some other type `B` to type `A`, you can effectively "re-use" your `OrderingComparer` * for type `B`. Also referred to commonly as `contramap`, because the mapping is going * from `B`&rarr;`A`, not from `A`&rarr;`B`. * * @group Utils * @group Constructors * * @param known The `OrderingComparer` that you already have. * @param map The function that can map from `B`&rarr;`A`. * * @returns A new `OrderingComparer` instance. */ export const deriveFrom = <A, B>( known: OrderingComparer<A>, map: (b: B) => A ): OrderingComparer<B> => ({ compare: (b1, b2) => (b1 === b2 ? 0 : known.compare(map(b1), map(b2))), }) /** * The default `OrderingComparer`. Converts both values to strings (if they * are not already) and does the default ASCII-based alphabetical comparison. * * @group Primitives */ export const Default: OrderingComparer<never> = ofCompare((a1, a2) => { const a1String: string = S.isString(a1) ? a1 : globalThis.String(a1) const a2String: string = S.isString(a2) ? a2 : globalThis.String(a2) return a1String < a2String ? -1 : a1String > a2String ? 1 : 0 }) /** * Combine or merge multiple `OrderingComparer`s together **in a specific order**. * Conceptually, this means, "Sort these values by this first, then this, then this" * and so on. * * For example if you have an `OrderingComparer` that sorts strings alphabetically in * a case-insensitive manner (say, `alphabeticalCiComparer`) and an `OrderingComparer` * that sorts strings by their length (say, `lengthComparer`), you could generate a new * "composite" `OrderingComparer` that sorts alphabetically (case-insensitive) **and * then by** length. * * @example * const alphabeticalCiThenLengthComparer = * OrderingComparer.getComposite(alphabeticalCiComparer, lengthComparer) * * @group Utils * * @remarks * If no comparers are passed, will default to {@link Default} * * @returns A new `OrderingComparer` instance. */ export const getComposite = <A>( ...comparers: readonly OrderingComparer<A>[] ): OrderingComparer<A> => { /* c8 ignore next 3 */ if (comparers.length < 1) { return Default } return ofCompare((a1, a2) => comparers.reduce<CompareResult>( (result, nextComparer) => result !== 0 ? result : nextComparer.compare(a1, a2), 0 ) ) } /** * An `OrderingComparer` for the built-in `number` type, in ascending order. * * @group Primitives */ export const Number: OrderingComparer<number> = ofCompare((n1, n2) => n2 - n1 > 0 ? -1 : 1 ) /** * An `OrderingComparer` for the built-in `string` type. Equivalent to {@link Default}. * * @group Primitives */ export const String: OrderingComparer<string> = Default /** * An `OrderingComparer` for the built-in `date` type, in ascending order. * * @group Primitives */ export const Date: OrderingComparer<Date> = deriveFrom(Number, date => date.valueOf()) /** * Get a combined `OrderingComparer` and `EqualityComparer` by using the check, * "Does the compare return `0`?" as the equals function. This produces a type * that is compatible with `Ord` from `fp-ts`. * * @returns A new instance that implements both `EqualityComparer` and `OrderingComparer` * * @group Utils */ export const deriveEqualityComparer = <A>( orderingComparer: OrderingComparer<A>
): OrderingComparer<A> & EqualityComparer<A> => ({
compare: orderingComparer.compare, equals: (a1, a2) => a1 === a2 || orderingComparer.compare(a1, a2) === 0, }) /** * Get whether the _first_ value is **greater than** the _second_ value. * * @param orderingComparer The `OrderingComparer` to use for the comparison. * * @group Comparisons */ export const gt = <A>({ compare }: OrderingComparer<A>) => (first: A, second: A): boolean => compare(first, second) === 1 /** * Get whether the _first_ value is **greater than or equal to** the _second_ value. * * @param orderingComparer The `OrderingComparer` to use for the comparison. * * @group Comparisons */ export const geq = <A>({ compare }: OrderingComparer<A>) => (first: A, second: A): boolean => compare(first, second) >= 0 /** * Get whether the _first_ value is **less than** the _second_ value. * * @param orderingComparer The `OrderingComparer` to use for the comparison. * * @group Comparisons */ export const lt = <A>({ compare }: OrderingComparer<A>) => (first: A, second: A): boolean => compare(first, second) === -1 /** * Get whether the _first_ value is **less than or equal to** the _second_ value. * * @param orderingComparer The `OrderingComparer` to use for the comparison. * * @group Comparisons */ export const leq = <A>({ compare }: OrderingComparer<A>) => (first: A, second: A): boolean => compare(first, second) <= 0 /** * Get whether the value is between the upper and lower bound (inclusive). * * @group Comparisons */ export const isBetween = <A>(orderingComparer: OrderingComparer<A>) => (lowerBound: A, upperBound: A) => (a: A): boolean => geq(orderingComparer)(a, lowerBound) && leq(orderingComparer)(a, upperBound) /* c8 ignore start */ /** @ignore */ export const OrderingComparer = { ofCompare, reverse, deriveFrom, Default, Number, String, Date, getComposite, deriveEqualityComparer, gt, geq, lt, leq, isBetween, } /* c8 ignore end */
src/OrderingComparer.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/NonEmptyArray.ts", "retrieved_chunk": " * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison.\n *\n * @returns A new `EqualityComparer` instance\n */\nexport const getEqualityComparer = <A>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<NonEmptyArray<A>> =>\n EqualityComparer.ofEquals((arr1, arr2) => {", "score": 0.9085968732833862 }, { "filename": "src/Result.ts", "retrieved_chunk": " * @group Utils\n *\n * @param equalityComparerA The `EqualityComparer` to use for the inner ok value.\n * @param equalityComparerE The `EqualityComparer` to use for the inner err value.\n *\n * @returns A new `EqualityComparer` instance\n */\nexport const getEqualityComparer = <A, E>(\n equalityComparerA: EqualityComparer<A>,\n equalityComparerE: EqualityComparer<E>", "score": 0.8903176784515381 }, { "filename": "src/EqualityComparer.ts", "retrieved_chunk": " }\n return true\n })\n/**\n * The default `EqualityComparer`, which uses reference (triple equals) equality.\n *\n * @group Primitives\n */\nexport const Default: EqualityComparer<never> = Object.freeze(\n ofEquals((a1, a2) => a1 === a2)", "score": 0.8894575238227844 }, { "filename": "src/NonEmptyArray.ts", "retrieved_chunk": " */\nexport const sort =\n <A>(orderingComparer: OrderingComparer<A> = OrderingComparer.Default) =>\n (as: NonEmptyArray<A>): NonEmptyArray<A> =>\n as.slice(0).sort(orderingComparer.compare) as unknown as NonEmptyArray<A>\n/**\n * Get an `EqualityComparer` that represents structural equality for a non-empty array\n * of type `A` by giving this function an `EqualityComparer` for each `A` element.\n *\n * @group Equality", "score": 0.8867408633232117 }, { "filename": "src/EqualityComparer.ts", "retrieved_chunk": " *\n * @group Utils\n * @group Constructors\n *\n * @param known The `EqualityComparer` that you already have.\n * @param map The function that can map from `B`&rarr;`A`.\n *\n * @returns A new `EqualityComparer` instance.\n */\nexport const deriveFrom = <A, B>(", "score": 0.8715361952781677 } ]
typescript
): OrderingComparer<A> & EqualityComparer<A> => ({
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else if (isErr(results[1])) { return err(results[1].err) } else { return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => {
if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) {
return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/NonEmptyArray.ts", "retrieved_chunk": " * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison.\n *\n * @returns A new `EqualityComparer` instance\n */\nexport const getEqualityComparer = <A>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<NonEmptyArray<A>> =>\n EqualityComparer.ofEquals((arr1, arr2) => {", "score": 0.8855172395706177 }, { "filename": "src/Nullable.ts", "retrieved_chunk": " * equals(4, 4) // => true\n * equals(4, 5) // => false\n * ```\n */\nexport const getEqualityComparer = <A extends NonNullish>(\n equalityComparer: EqualityComparer<A>\n) =>\n EqualityComparer.ofEquals<Nullable<A>>(\n (a1, a2) =>\n (a1 == null && a2 == null) ||", "score": 0.866290271282196 }, { "filename": "src/Array.ts", "retrieved_chunk": " * const eq = Array.getEqualityComparer(EqualityComparer.Number)\n * eq.equals([1, 2, 3], [1, 2, 3]) // => true\n * eq.equals([1, 3], [3, 1]) // => false\n */\nexport const getEqualityComparer = <A>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<readonly A[]> =>\n EqualityComparer.ofEquals((arr1, arr2) => {\n if (isEmpty(arr1) && isEmpty(arr2)) {\n return true", "score": 0.852737545967102 }, { "filename": "src/EqualityComparer.ts", "retrieved_chunk": " * @returns A new `EqualityComparer` instance.\n */\nexport const ofStruct = <A extends object>(\n struct: EqualityComparerRecord<A>\n): EqualityComparer<Readonly<A>> =>\n ofEquals((a1, a2) => {\n for (const key in struct) {\n if (!struct[key].equals(a1[key], a2[key])) {\n return false\n }", "score": 0.8476202487945557 }, { "filename": "src/Option.ts", "retrieved_chunk": "export const getEqualityComparer = <A extends NonNullish>({\n equals,\n}: EqualityComparer<A>): EqualityComparer<Option<A>> =>\n // `ofEquals` has a built-in reference equality check, which captures the None/None case\n EqualityComparer.ofEquals((opt1, opt2) =>\n pipe(\n [opt1, opt2] as const,\n map2((a1: A, a2: A) => equals(a1, a2)),\n defaultValue(false)\n )", "score": 0.8452998399734497 } ]
typescript
if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) {
/** See [Enums considered harmful](https://www.youtube.com/watch?v=jjMbPt_H3RQ) for the motivation behind this custom type. (Also worth noting is that in TypeScript 5.0 [all Enums are considered unions](https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#all-enums-are-union-enums).) Similar to [variants](variants.md) for disciminated unions, `enumOf` allows you to more easily and safely create and work with enums in TypeScript. ## Basic Example ```ts export const MyEnum = enumOf( { Dog = "Dog", Cat = "Cat", ZEBRA = 1234, } as const, // the `as const` won't be required in TypeScript 5.0 "MyEnum" // friendly name is optional; used to generate helpful parser errors ) export type MyEnum = EnumOf<typeof MyEnum> // => "Dog" | "Cat" | 1234 ``` ## Methods ### Standard enum-style accessors ```ts const dog = MyEnum.Dog // => "Dog" const zebra = MyEnum.ZEBRA // => 1234 ``` ### Values Access array of all valid values, correctly typed (but without any ordering guarantees). ```ts const myEnumValues = MyEnum.values // => ["Dog", "Cat", 1234] ``` ### Parser Get a safe parser function for this enum automagically! ```ts const parsed = MyEnum.parse("cat") // => a `Result<MyEnum, string>`, in this case `Result.ok("Cat")` ``` ### Match See `match` in the {@link Variants} module docs for more details on matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.match({ Dog: "woof woof", Cat: () => "meow", ZEBRA: "is my skin white with black stripes or black with white stripes??", }) speak(myEnum) ``` ### MatchOrElse See `matchOrElse` in the {@link Variants} module docs for more details on partial matchers. ```ts const speak: (e: MyEnum) => string = MyEnum.matchOrElse({ Dog: "woof woof", Cat: () => "meow", orELse: "I cannot speak.", }) speak(myEnum) ``` @module Enums */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Result } from "./Result" import { String } from "./string" import { Option } from "./Option" import { pipe, flow } from "./Composition" import { Array } from "./Array" import { Identity, NonNullish } from "./prelude" /** @ignore */ type StringKeys<T extends object> = Extract<keyof T, string> /** * A plain object that serves as the definition of the enum type. * Until TypeScript 5.0 is released, you need to specify `as const` * on this object definition. */ type RawEnum = Record<string, string | number> /** @ignore */ type StringKeyValues<T extends RawEnum> = Identity<T[StringKeys<T>]> /** @ignore */ type EnumMatcher<A, R extends RawEnum> = { readonly [Label in StringKeys<R>]: (() => A) | A } /** @ignore */ type PartialEnumMatcher<A, R extends RawEnum> = Partial<EnumMatcher<A, R>> & { readonly orElse: (() => A) | A } type EnumMatch<R extends RawEnum> = <A>( matcher: EnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A type EnumMatchOrElse<R extends RawEnum> = <A>( matcher: PartialEnumMatcher<A, R> ) => (value: StringKeyValues<R>) => A /** * The output of the {@link enumOf} function. Produces an object that serves both as * the enum as well as a namespace for helper functions related to that enum. */ type EnumModule<R extends RawEnum> = Identity< { readonly [Label in StringKeys<R>]: R[Label] } & { /** * Returns a readonly array containing the set of all possible enum values. No * guarantees are made regarding the order of items in the resultant array. */ readonly values: ReadonlyArray<StringKeyValues<R>> /** * For string enum values, the parse function will trim and coerce values to lowercase * before comparison. (This has no effect on numeric enum values.) Thus, if an * enum is defined as `'Yes' | 'No'`, this decoder will parse `'yes'`, `' yES'`, * and `' YES '` correctly into the canonical `'Yes'` enum value. */ readonly parse: (u: unknown) => Result<StringKeyValues<R>, string> /** * Use this function for an exhaustive case check that doesn't require using * a switch/case block or any kind of assertExhaustive check. */ readonly match: EnumMatch<R> /** * Use this function for a partial case check that doesn't require using * a switch/case block. */ readonly matchOrElse: EnumMatchOrElse<R> } > /** * Gets the union type representing all possible enum values. */ export type EnumOf<T> = T extends EnumModule<infer R> ? StringKeyValues<R> : [never, "Error: T must be an EnumModule"] const getParserErrorMessage = <T extends RawEnum>( enumValues: EnumModule<T>["values"], enumFriendlyName: string ) => `Must be an enum value in the set ${enumFriendlyName}{ ${enumValues.join(", ")} }` const toTrimmedLowerCase = (a: string | number) => pipe( Option.some(a), Option.refine(String.isString), Option.map(flow(String.trim, String.toLowerCase)), Option.defaultValue(a) ) const isStringOrNumber = (u: NonNullish): u is string | number => typeof u === "string" || typeof u === "number" const getParseFn = <R extends RawEnum>(enumValues: EnumModule<R>["values"], enumFriendlyName: string) => (u: unknown): Result<StringKeyValues<R>, string> => pipe( Option.
ofNullish(u), Result.ofOption( () => `Enum${
enumFriendlyName ? ` ${enumFriendlyName}` : "" } cannot be null/undefined` ), Result.refine( isStringOrNumber, () => `Enum${ enumFriendlyName ? ` ${enumFriendlyName}` : "" } must be a string or number` ), Result.map(toTrimmedLowerCase), Result.bind(testVal => pipe( enumValues, Array.find(val => toTrimmedLowerCase(val) === testVal), Option.match({ some: a => Result.ok(a), none: () => Result.err( getParserErrorMessage(enumValues, enumFriendlyName) ), }) ) ) ) const isFunc = (f: unknown): f is (...args: any[]) => any => typeof f === "function" const getMatchFn = <R extends RawEnum>(raw: R): EnumMatch<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (!Object.hasOwn(matcher, enumLabel)) { throw new TypeError( `Expected a matcher containing a case for '${enumLabel}'.` ) } const matcherBranch = matcher[enumLabel] return isFunc(matcherBranch) ? matcherBranch() : matcherBranch } const getMatchOrElseFn = <R extends RawEnum>(raw: R): EnumMatchOrElse<R> => matcher => value => { const enumEntry = Object.entries(raw).find(([, v]) => v === value) if (!enumEntry) { throw new TypeError( `Expected to match against an enum where '${value}' is a valid value.` ) } const enumLabel = enumEntry[0] if (Object.hasOwn(matcher, enumLabel)) { const branch = matcher[enumLabel] // eslint-disable-next-line @typescript-eslint/no-unsafe-return return isFunc(branch) ? branch() : branch } return isFunc(matcher.orElse) ? matcher.orElse() : matcher.orElse } /** * Generates an "enum module" from a raw object. For motivation behind using a custom * generative function instead of the built-in `enum` types, see [this video](https://youtu.be/jjMbPt_H3RQ). * * This function augments a raw "enum object" with several useful capabilities: `values`, `parse`, `match`, * and `matchOrElse`. * - `values` contains the list of valid enum values * - `parse` is a parser funciton auto-magically created for this enum * - `match` is a pipeable function that allows exhaustive pattern matching * - `matchOrElse` is a pipeable function that allows inexhaustive pattern matching * * @remarks * You can use the `parse` function together with `io-ts` to easily create a decoder for this enum. * * @example * ```ts * export const MyEnum = enumOf({ * Dog = 'Dog', * Cat = 'Cat', * ZEBRA = 1234, * } as const, 'MyEnum') // => friendly name optional; used to generate helpful decoder errors * export type MyEnum = EnumOf<typeof MyEnum>; //=> 'Dog' | 'Cat' | 1234 * * // Standard enum-style accessors * const dog = MyEnum.Dog; // => 'Dog' * const zebra = MyEnum.ZEBRA; // => 1234 * * // Access array of all valid values, correctly typed * const myEnumValues = MyEnum.values; // => ['Dog', 'Cat', 1234] * * // Get a decoder instance for this enum automagically * const myDecoder = MyEnum.decoder; // => a `D.Decoder<unknown, 'Dog' | 'Cat' | 1234>` * * // Match an enum value against all its cases (compiler ensures exhaustiveness) * const value: MyEnum = 'Cat'; * const matchResult = pipe( * value, * MyEnum.match({ * Dog: 'woof woof', * Cat: () => 'meow', * ZEBRA: 'is my skin white with black stripes or black with white stripes??' * }) * ) // => 'meow' * ``` */ export const enumOf = <T extends RawEnum>( raw: T, enumFriendlyName = "" ): EnumModule<T> => { const entriesWithStringKeys = Object.entries(raw).reduce( (acc, [label, value]) => ({ ...acc, [label]: value, }), {} ) const values = Object.values(raw) return { ...entriesWithStringKeys, values, parse: getParseFn(values, enumFriendlyName), match: getMatchFn(raw), matchOrElse: getMatchOrElseFn(raw), } as unknown as EnumModule<T> }
src/Enums.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Option.ts", "retrieved_chunk": " * none: 0,\n * })\n * ) // => 84\n */\nexport const match =\n <A extends NonNullish, R>(matcher: OptionMatcher<A, R>) =>\n (option: Option<A>) => {\n switch (option._tag) {\n case \"Some\":\n return getMatcherResult(matcher.some, option.some)", "score": 0.8239696621894836 }, { "filename": "src/Option.ts", "retrieved_chunk": " *\n * @example\n * ```\n * const isString = (u: unknown): u is string => typeof u === \"string\"\n *\n * pipe(\n * Option.some(\"cheese\" as any), // Option<any>\n * Option.refine(isString), // Option<string> (type is narrowed by the guard)\n * Option.map(s => s.length) // Option<number> (TS infers the type of `s`)\n * ) // => Option.some(6)", "score": 0.8185685873031616 }, { "filename": "src/Nullable.ts", "retrieved_chunk": " * null,\n * Nullable.defaultWith(() => 42)\n * ) // => 42\n */\nexport const defaultWith =\n <A extends NonNullish>(f: () => A) =>\n (nullable: Nullable<A>): NonNullable<A> =>\n nullable != null ? nullable : f()\n/**\n * Similar to `Option.map`. Uses the given function to map the nullable value", "score": 0.8120137453079224 }, { "filename": "src/Result.ts", "retrieved_chunk": " * Result.map(n => n + 1), // inner value is unchanged\n * Result.defaultValue(0)\n * ) // => 24\n * ```\n */\nexport const tee =\n <A>(f: (a: A) => void) =>\n <E>(result: Result<A, E>): Result<A, E> =>\n pipe(\n result,", "score": 0.810065507888794 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": "}\nconst isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R =>\n typeof caseFn !== \"function\"\nconst getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) =>\n isRawValue(match) ? match : match(arg)\nconst objHasOptionalProp = <T extends object, P extends keyof T>(\n prop: P,\n obj: T\n): obj is Identity<T & Required<{ [key in P]: T[P] }>> => Object.hasOwn(obj, prop)\n/**", "score": 0.8094224333763123 } ]
typescript
ofNullish(u), Result.ofOption( () => `Enum${
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Mixed } from "./component"; import type { Mixer } from "./mixer"; import { mixer } from "./mixer"; import type { Impl } from "./provider"; import { impl } from "./provider"; describe("Mixer", () => { describe("new", () => { /* eslint-disable @typescript-eslint/naming-convention */ type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("creates an instance if there is no error", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type M = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); it("reports missing dependencies if some dependencies are missing", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M["new"], | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "bar"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); }); it("reports incompatible dependencies if some dependencies are incompatible", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type Bar2 = { getBar2: () => string }; type Bar2Component = Component<"bar", Bar2>; type Bar2Impl = Impl<Bar2Component, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl, BazImpl, Bar2Impl]>; assertType< Equals< M["new"], { __incompatibleDependenciesError?: { reason: "some dependencies are incompatible"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; actualType: Bar2; }, ]; }; } > >(); }); it("reports missing dependencies if some dependencies are possibly missing", () => { type FooImpl = Impl<FooComponent, [BarComponent]>; type BarImpl = Impl<BarComponent>; type BarBazImpl = Impl<BarComponent | BazComponent>; type M1 = Mixer<[FooImpl, BarBazImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarBazImpl, BarImpl]>; assertType< Equals<M2["new"], () => Mixed<[FooComponent, BarComponent | BazComponent, BarComponent]>> >(); }); it("allows creating an instance if any possible combination of dependencies is provided", () => { type FooImpl = Impl<FooComponent, [BarComponent] | [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: | [ { name: "bar"; expectedType: Bar; }, ] | [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType<Equals<M2["new"], () => Mixed<[FooComponent, BarComponent]>>>(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType<Equals<M3["new"], () => Mixed<[FooComponent, BazComponent]>>>(); }); it("reports missing dependencies unless all possible dependencies are provided", () => { type FooImpl = Impl<FooComponent, [BarComponent]> | Impl<FooComponent, [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ | { name: "bar"; expectedType: Bar; } | { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M2["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType< Equals< M3["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M4 = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M4["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); /* eslint-enable @typescript-eslint/naming-convention */ }); }); describe("mixer", () => { type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("mixes components and creates a mixed instance", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const
m = mixer(foo, bar, baz);
assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); it("overrides previous mixed components", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const baz2 = impl<BazComponent>("baz", () => ({ getBaz: () => false, })); const m = mixer(foo, bar, baz).with(baz2); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz, typeof baz2]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(42); }); it("throws if a component is referenced during its initialization", () => { // foo and bar reference each other during initialization const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", ({ foo }) => ({ getBar: () => foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).toThrow("'foo' is referenced during its initialization"); }); it("does not throw if a component is referenced after its initialization, even if there is a circular dependency", () => { // foo references bar during its initialization, while bar defers referencing foo until it is actually used // (this is not a good example though; it loops forever if you call foo.getFoo() or bar.getBar()) const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", deps => ({ getBar: () => deps.foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).not.toThrow(); }); it("accepts classes as compoent factories", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>( "foo", class FooImpl { private bar: Bar; private baz: Baz; constructor({ bar, baz }: Mixed<[BarComponent, BazComponent]>) { this.bar = bar; this.baz = baz; } getFoo(): number { return this.baz.getBaz() ? this.bar.getBar().length : 42; } } ); const bar = impl<BarComponent, [BazComponent]>( "bar", class BarImpl { private baz: Baz; constructor({ baz }: Mixed<[BazComponent]>) { this.baz = baz; } getBar(): string { return this.baz.getBaz() ? "Hello" : "Bye"; } } ); const baz = impl<BazComponent>( "baz", class BazImpl { getBaz(): boolean { return true; } } ); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); });
src/mixer.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.spec.ts", "retrieved_chunk": " type BarComponent = Component<\"bar\", { getBar: () => string }>;\n const foo = impl<FooComponent, [BarComponent]>(\"foo\", ({ bar }) => ({\n getFoo: () => bar.getBar().length,\n }));\n assertType<Equals<typeof foo, Impl<FooComponent, [BarComponent]>>>();\n expect(foo.name).toBe(\"foo\");\n const value = invokecFactory(foo.factory, {\n bar: {\n getBar: () => \"Hello\",\n },", "score": 0.8815181255340576 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " it(\"returns a provider type that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n Impl<FooComponent, [BarComponent, BazComponent]>,\n Provider<\n \"foo\",\n { getFoo: () => number },", "score": 0.8746156692504883 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.8721681833267212 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " });\n});\ndescribe(\"ImplArgs\", () => {\n it(\"returns a tuple that has the same shape of the provider that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n ImplArgs<FooComponent, [BarComponent, BazComponent]>,", "score": 0.865315318107605 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.8589169979095459 } ]
typescript
m = mixer(foo, bar, baz);
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else if (isErr(results[1])) {
return err(results[1].err) } else {
return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => { if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Array.ts", "retrieved_chunk": " */\nexport const chooseR =\n <A, E, B>(f: (a: A) => Result<B, E>) =>\n (as: readonly A[]): readonly B[] => {\n const bs: B[] = []\n for (let i = 0; i < as.length; i++) {\n const result = f(as[i])\n if (Result.isOk(result)) {\n bs.push(result.ok)\n }", "score": 0.8076894283294678 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": "export const mapBoth =\n <A1, A2, E1, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) =>\n (async: AsyncResult<A1, E1>) =>\n () =>\n async().then(Result.mapBoth(mapOk, mapErr))\n/**\n * Maps the wrapped `Ok` value using a given function that\n * also returns an AsyncResult, and flattens the result.\n * Also commonly known as `flatpMap`.\n *", "score": 0.776475727558136 }, { "filename": "src/Option.ts", "retrieved_chunk": " (options: readonly [Option<A>, Option<B>]): Option<C> => {\n if (isSome(options[0]) && isSome(options[1])) {\n return some(map(options[0].some, options[1].some))\n }\n return none\n }\n/**\n * Returns a Some containing the value returned from the map function\n * if all three `Option`s are `Some`s. Otherwise, returns `None`.\n *", "score": 0.7721732258796692 }, { "filename": "src/Option.ts", "retrieved_chunk": " <\n A extends NonNullish,\n B extends NonNullish,\n C extends NonNullish,\n D extends NonNullish\n >(\n map: (a: A, b: B, c: C) => D\n ) =>\n (options: readonly [Option<A>, Option<B>, Option<C>]): Option<D> => {\n if (isSome(options[0]) && isSome(options[1]) && isSome(options[2])) {", "score": 0.7628462314605713 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " return getMatcherResult(matcher.inProgress, undefined)\n case \"NotStarted\":\n return getMatcherResult(matcher.notStarted, undefined)\n case \"Resolved\":\n return pipe(\n deferredResult.resolved,\n Result.match({\n ok: a => getMatcherResult(matcher.resolvedOk, a),\n err: e => getMatcherResult(matcher.resolvedErr, e),\n })", "score": 0.7622555494308472 } ]
typescript
return err(results[1].err) } else {
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default: return assertExhaustive(result) } } /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[
2].ok)) } else if (isErr(results[0])) {
return err(results[0].err) } else if (isErr(results[1])) { return err(results[1].err) } else { return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => { if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Array.ts", "retrieved_chunk": " */\nexport const chooseR =\n <A, E, B>(f: (a: A) => Result<B, E>) =>\n (as: readonly A[]): readonly B[] => {\n const bs: B[] = []\n for (let i = 0; i < as.length; i++) {\n const result = f(as[i])\n if (Result.isOk(result)) {\n bs.push(result.ok)\n }", "score": 0.8380213975906372 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": "export const mapBoth =\n <A1, A2, E1, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) =>\n (async: AsyncResult<A1, E1>) =>\n () =>\n async().then(Result.mapBoth(mapOk, mapErr))\n/**\n * Maps the wrapped `Ok` value using a given function that\n * also returns an AsyncResult, and flattens the result.\n * Also commonly known as `flatpMap`.\n *", "score": 0.8317484855651855 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": " * Async.start // Promise<Result<{}, Error>>\n * )\n * // returns Result.ok({}) if everything succeeds\n * // otherwise returns Result.err(Error) if something\n * // fell down along the way\n */\nexport const bind =\n <A, B, E>(f: (a: A) => AsyncResult<B, E>) =>\n (async: AsyncResult<A, E>): AsyncResult<B, E> =>\n async () => {", "score": 0.8166398406028748 }, { "filename": "src/Option.ts", "retrieved_chunk": " <\n A extends NonNullish,\n B extends NonNullish,\n C extends NonNullish,\n D extends NonNullish\n >(\n map: (a: A, b: B, c: C) => D\n ) =>\n (options: readonly [Option<A>, Option<B>, Option<C>]): Option<D> => {\n if (isSome(options[0]) && isSome(options[1]) && isSome(options[2])) {", "score": 0.8138924837112427 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": "export const teeErr =\n <E>(f: (a: E) => void) =>\n <A>(async: AsyncResult<A, E>): AsyncResult<A, E> =>\n Async.tee<Result<A, E>>(Result.teeErr(f))(async)\n/* c8 ignore start */\n/** @ignore */\nexport const AsyncResult = {\n ok,\n err,\n map,", "score": 0.8129596710205078 } ]
typescript
2].ok)) } else if (isErr(results[0])) {
/** * The `Result` type represents the outcome of a completed operation * that either succeeded with some `Ok` value (also called a "success" * or "right" value), or failed with some `Err` value (also called a * "failure" or "left" value). * * Generally speaking, `Result` is not intended to _replace_ exception * handling, but to augment it, so that exceptions can be used to handle * truly _exceptional_ things. (i.e., Is it really exceptional that a * network request failed?) * * This API has been optimized for use with left-to-right function composition * using `pipe` and `flow`. * * @example * ``` * pipe( * Result.tryCatch(() => readFileMightThrow()), * Result.mapErr(FileError.create), * Result.bind(fileText => pipe( * Result.tryCatch(() => transmitMightThrow(fileText)), * Result.mapErr(FileError.create) * )), * Result.map(transmitResponse => transmitResponse?.status), * Result.defaultValue("failed") * ) * // may return, e.g., "pending" if everything worked * // or "failed" if something fell down along the way * ``` * * @module Result */ /* eslint-disable @typescript-eslint/no-empty-interface */ import { Tagged, assertExhaustive, Refinement, NonNullish } from "./prelude" import { Option } from "./Option" import { flow, pipe } from "./Composition" import { EqualityComparer } from "./EqualityComparer" export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} export interface Err<E> extends Tagged<"Err", { err: E }> {} export type Result<A, E> = Ok<A> | Err<E> /** * Construct a new Ok instance. * * @group Constructors * * @returns A new Ok instance containing the given value. */ export const ok = <A, E = never>(ok: A): Result<A, E> => ({ _tag: "Ok", ok, }) /** * Construct a new Err instance. * * @group Constructors * * @returns A new Err instance with the given value. */ export const err = <E, A = never>(err: E): Result<A, E> => ({ _tag: "Err", err, }) /** * Alias for {@link ok}. * * @group Constructors */ export const of = ok /** * @ignore */ interface ResultMatcher<A, E, R> { readonly ok: R | ((ok: A) => R) readonly err: R | ((err: E) => R) } const isRawValue = <A, E, R>(caseFn: R | ((ok: A) => R) | ((err: E) => E)): caseFn is R => typeof caseFn !== "function" const getMatcherResult = <T, R>(match: ((t: T) => R) | R, arg: T) => isRawValue(match) ? match : match(arg) /** * Exhaustive pattern match against a `Result` to "unwrap" its inner * value. Pass a matcher function with cases for `ok` and `err` that * can either be lambdas or raw values. * * @group Pattern Matching * * @example * ``` * pipe( * Result.err("failure"), * Result.match({ * ok: a => `${a.length}`, * err: s => `${s}!` * }) * ) // => "failure!" * ``` */ export const match = <A, E, R>(matcher: ResultMatcher<A, E, R>) => (result: Result<A, E>) => { switch (result._tag) { case "Ok": return getMatcherResult(matcher.ok, result.ok) case "Err": return getMatcherResult(matcher.err, result.err) /* c8 ignore next 2 */ default:
return assertExhaustive(result) }
} /** * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use * the given `onFail` function to produce an error branch. * * @group Utils * @group Filtering * * @example * ``` * const isCat = (s: string): s is "cat" => s === "cat" * pipe( * Result.ok("dog"), * Result.refine(isCat, a => `"${a}" is not "cat"!`) * ) // => Result.err('"dog" is not "cat"!') * ``` */ export const refine = <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) => (result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => (refinement(a) ? ok(a) : err(onFail(a))), err: e => err(e), }) ) /** * Map the inner `Ok` value using the given function and * return a new `Result`. Passes `Err` values through as-is. * * @group Mapping * * @example * pipe( * Result.ok(2), * Result.map(n => n + 3) * ) // => Result.ok(5) */ export const map = <A, B>(f: (a: A) => B) => <E>(result: Result<A, E>): Result<B, E> => pipe( result, match({ ok: a => ok(f(a)), err: e => err(e), }) ) /** * Map the inner `Err` value using the given function and * return a new `Result`. `Ok` values are passed through as-is. * * @group Mapping * * @example * pipe( * Result.err("cheese melted"), * Result.mapErr(s => s.length) * ) // => Result.err(13) */ export const mapErr = <E1, E2>(f: (e: E1) => E2) => <A>(result: Result<A, E1>) => pipe( result, match({ ok: a => ok(a), err: e => err(f(e)), }) ) /** * Map both branches of the Result by specifying a lambda * to use in either case. Equivalent to calling {@link map} followed * by {@link mapErr}. * * @group Mapping */ export const mapBoth = <A1, E1, A2, E2>(mapOk: (a: A1) => A2, mapErr: (e: E1) => E2) => match<A1, E1, Result<A2, E2>>({ ok: a => ok(mapOk(a)), err: e => err(mapErr(e)), }) /** * Return the inner `Ok` value or the given default value * if the Result is an Err. * * @group Pattern Matching */ export const defaultValue = <A>(a: A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: a, }) ) /** * Return the inner `Ok` value or use the given lambda * to compute the default value if the `Result` is an `Err`. * * @group Pattern Matching */ export const defaultWith = <A>(f: () => A) => <E>(result: Result<A, E>) => pipe( result, match({ ok: a => a, err: f, }) ) /** * Maps the inner `Ok` value using a function that * also returns a `Result`, and flattens the result. * `Err` values are passed through as-is. This function * is also referred to as `flatMap`. * * @group Mapping * * @example * pipe( * Result.ok("a"), * Result.bind(s => * s === "a" ? Result.ok("got an a!") : Result.err("not an a") * ), * Result.defaultValue("") * ) // => "got an a!" */ export const bind = <A, E, B>(f: (a: A) => Result<B, E>) => match<A, E, Result<B, E>>({ ok: f, err: e => err(e), }) /** * Alias for {@link bind}. * * @group Mapping */ export const flatMap = bind /** * A type guard (a.k.a. `Refinement`) that holds if the result * is an `Ok`. Allows the TypeScript compiler to narrow the type * and allow type-safe access to `.ok`. * * @group Type Guards */ export const isOk = <A, E = never>(result: Result<A, E>): result is Ok<A> => result._tag === "Ok" /** * A type guard (a.k.a. `Refinement`) that holds if the result is * an `Err`. Allows the TypeScript compiler to narrow the type and * allow safe access to `.err`. * * @group Type Guards */ export const isErr = <E, A = never>(result: Result<A, E>): result is Err<E> => result._tag === "Err" /** * Map a tuple of `Result`s. * * If given two `Ok` values, uses the given mapper function and produces * a new `Ok` instance with the result. If either of the `Result`s are an * `Err`, returns an `Err`. If both results are an `Err`, returns the first * one and ignores the second. * * @remarks * This is effectively a shortcut to pattern matching a 2-tuple of Results. * * @group Mapping */ export const map2 = <A, B, C>(map: (a: A, b: B) => C) => <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => { if (isOk(results[0]) && isOk(results[1])) { return ok(map(results[0].ok, results[1].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else { return err((results[1] as Err<E>).err) } } /** * Map a 3-tuple of `Result`s. * * If given three `Ok` values, uses the given mapper function and returns * a new `Ok` value with the result. If any of the `Result`s are an `Err`, * returns an `Err`. * * If multiple `Result`s are an `Err`, returns the first one found and * ignores the others. * * @remarks * This is effectively a shortcut to pattern matching a 3-tuple of Results. * * @group Pattern Matching */ export const map3 = <A, B, C, D>(map: (a: A, b: B, c: C) => D) => <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => { if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) { return ok(map(results[0].ok, results[1].ok, results[2].ok)) } else if (isErr(results[0])) { return err(results[0].err) } else if (isErr(results[1])) { return err(results[1].err) } else { return err((results[2] as Err<E>).err) } } /* eslint-disable func-style */ /** * Attempts to invoke a function that may throw. If the function * succeeds, returns an Ok with the result. If the function throws, * returns an Err containing the thrown Error, optionally transformed. * * @group Utils * * @param onThrow * Optional. If given, accepts the thrown `unknown` object and produces * the Err branch. If omitted, the thrown object will be stringified and * wrapped in a new Error instance if it is not already an Error instance. */ export function tryCatch<A>(mightThrow: () => A): Result<A, Error> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow: (thrown: unknown) => E ): Result<A, E> export function tryCatch<A, E = unknown>( mightThrow: () => A, onThrow?: (err: unknown) => E // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Result<A, any> { const toError = (err: unknown) => (err instanceof Error ? err : Error(String(err))) try { return ok(mightThrow()) } catch (err) { if (onThrow != null) { return Result.err(onThrow(err)) } return Result.err(toError(err)) } } /* eslint-enable func-style */ /** * Allows some arbitrary side-effect function to be called * using the wrapped `Ok` value. Useful for debugging and logging. * * @group Utils * * @param f Should not mutate its arguments. Use {@link map} if you * want to map the inner value of the Result instead. * * @example * ``` * pipe( * Result.ok(23), * Result.tee(console.log), // logs `23` * Result.map(n => n + 1), // inner value is unchanged * Result.defaultValue(0) * ) // => 24 * ``` */ export const tee = <A>(f: (a: A) => void) => <E>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => { f(a) return ok(a) }, err: e => err(e), }) ) /** * Allows some arbitrary side-effect function to be called * using the wrapped `Err` value. Useful for debugging and logging. * * @param f Should not mutate its arguments. Use {@link mapErr} if * you want to map the inner `Err` value. * * @group Utils * * @example * ``` * pipe( * Result.err("melted"), * Result.teeErr(console.log), // logs `melted` * Result.mapErr(s => s.length), // inner value is unchanged * ) // => Result.err(6) * ``` */ export const teeErr = <E>(f: (e: E) => void) => <A>(result: Result<A, E>): Result<A, E> => pipe( result, match({ ok: a => ok(a), err: e => { f(e) return err(e) }, }) ) /** * Converts an `Option` to a `Result`. * * @group Constructors * @group Utils * * @param onNone Used to convert a `None` branch into an `Err` branch. * * @returns a new `Result`. */ export const ofOption = <A extends NonNullish, E>(onNone: () => E) => Option.match<A, Result<A, E>>({ some: ok, none: flow(onNone, err), }) /** * Get an `EqualityComparer` for an `Result<A, E>` by giving this function an * `EqualityComparer` for type `A` and one for type `E`. Represents structural * (value-based) equality for the `Result` type. * * @group Equality * @group Utils * * @param equalityComparerA The `EqualityComparer` to use for the inner ok value. * @param equalityComparerE The `EqualityComparer` to use for the inner err value. * * @returns A new `EqualityComparer` instance */ export const getEqualityComparer = <A, E>( equalityComparerA: EqualityComparer<A>, equalityComparerE: EqualityComparer<E> ): EqualityComparer<Result<A, E>> => EqualityComparer.ofEquals((r1, r2) => { if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { return true } return pipe( [r1, r2] as const, map2((a1: A, a2: A) => equalityComparerA.equals(a1, a2)), defaultValue(false) ) }) /* c8 ignore start */ /** @ignore */ export const Result = { ok, of, err, isOk, isErr, match, map, map2, map3, mapErr, mapBoth, bind, flatMap, defaultValue, defaultWith, tryCatch, tee, teeErr, ofOption, getEqualityComparer, refine, } /* c8 ignore end */
src/Result.ts
fp-toolkit-fp-toolkit-a5f0d7d
[ { "filename": "src/Deferred.ts", "retrieved_chunk": " switch (deferred._tag) {\n case \"NotStarted\":\n return resultOrValue(matcher.notStarted)\n case \"InProgress\":\n return resultOrValue(matcher.inProgress)\n case \"Resolved\":\n return resultOrValue(matcher.resolved, deferred.resolved)\n /* c8 ignore next 2 */\n default:\n return assertExhaustive(deferred) as R", "score": 0.8728799819946289 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " return getMatcherResult(matcher.inProgress, undefined)\n case \"NotStarted\":\n return getMatcherResult(matcher.notStarted, undefined)\n case \"Resolved\":\n return pipe(\n deferredResult.resolved,\n Result.match({\n ok: a => getMatcherResult(matcher.resolvedOk, a),\n err: e => getMatcherResult(matcher.resolvedErr, e),\n })", "score": 0.8576215505599976 }, { "filename": "src/AsyncResult.ts", "retrieved_chunk": " err instanceof Error ? err : Error(String(err))\n try {\n return Result.ok(await mightThrow())\n } catch (err) {\n if (onThrow != null) {\n return Result.err(onThrow(err))\n }\n return Result.err(toError(err))\n }\n }", "score": 0.8265416622161865 }, { "filename": "src/Deferred.ts", "retrieved_chunk": " case \"InProgress\":\n return resultOrValue(\n matcher.inProgress != null ? matcher.inProgress : matcher.orElse\n )\n case \"Resolved\":\n return matcher.resolved != null\n ? resultOrValue(matcher.resolved, deferred.resolved)\n : resultOrValue(matcher.orElse)\n /* c8 ignore next 2 */\n default:", "score": 0.8255948424339294 }, { "filename": "src/DeferredResult.ts", "retrieved_chunk": " * resolvedErr: apiError => `Error was: ${ApiError.toString(apiError)}`\n * })\n * )\n * ```\n */\nexport const match =\n <A, E, R>(matcher: DeferredResultMatcher<A, E, R>) =>\n (deferredResult: DeferredResult<A, E>) => {\n switch (deferredResult._tag) {\n case \"InProgress\":", "score": 0.8239239454269409 } ]
typescript
return assertExhaustive(result) }
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Mixed } from "./component"; import type { Mixer } from "./mixer"; import { mixer } from "./mixer"; import type { Impl } from "./provider"; import { impl } from "./provider"; describe("Mixer", () => { describe("new", () => { /* eslint-disable @typescript-eslint/naming-convention */ type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("creates an instance if there is no error", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type M = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); it("reports missing dependencies if some dependencies are missing", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M["new"], | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "bar"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); }); it("reports incompatible dependencies if some dependencies are incompatible", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type Bar2 = { getBar2: () => string }; type Bar2Component = Component<"bar", Bar2>; type Bar2Impl = Impl<Bar2Component, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl, BazImpl, Bar2Impl]>; assertType< Equals< M["new"], { __incompatibleDependenciesError?: { reason: "some dependencies are incompatible"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; actualType: Bar2; }, ]; }; } > >(); }); it("reports missing dependencies if some dependencies are possibly missing", () => { type FooImpl = Impl<FooComponent, [BarComponent]>; type BarImpl = Impl<BarComponent>; type BarBazImpl = Impl<BarComponent | BazComponent>; type M1 = Mixer<[FooImpl, BarBazImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarBazImpl, BarImpl]>; assertType< Equals<M2["new"], () => Mixed<[FooComponent, BarComponent | BazComponent, BarComponent]>> >(); }); it("allows creating an instance if any possible combination of dependencies is provided", () => { type FooImpl = Impl<FooComponent, [BarComponent] | [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: | [ { name: "bar"; expectedType: Bar; }, ] | [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType<Equals<M2["new"], () => Mixed<[FooComponent, BarComponent]>>>(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType<Equals<M3["new"], () => Mixed<[FooComponent, BazComponent]>>>(); }); it("reports missing dependencies unless all possible dependencies are provided", () => { type FooImpl = Impl<FooComponent, [BarComponent]> | Impl<FooComponent, [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ | { name: "bar"; expectedType: Bar; } | { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M2["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType< Equals< M3["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M4 = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M4["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); /* eslint-enable @typescript-eslint/naming-convention */ }); }); describe("mixer", () => { type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("mixes components and creates a mixed instance", () => { const
foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({
getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); it("overrides previous mixed components", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const baz2 = impl<BazComponent>("baz", () => ({ getBaz: () => false, })); const m = mixer(foo, bar, baz).with(baz2); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz, typeof baz2]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(42); }); it("throws if a component is referenced during its initialization", () => { // foo and bar reference each other during initialization const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", ({ foo }) => ({ getBar: () => foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).toThrow("'foo' is referenced during its initialization"); }); it("does not throw if a component is referenced after its initialization, even if there is a circular dependency", () => { // foo references bar during its initialization, while bar defers referencing foo until it is actually used // (this is not a good example though; it loops forever if you call foo.getFoo() or bar.getBar()) const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", deps => ({ getBar: () => deps.foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).not.toThrow(); }); it("accepts classes as compoent factories", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>( "foo", class FooImpl { private bar: Bar; private baz: Baz; constructor({ bar, baz }: Mixed<[BarComponent, BazComponent]>) { this.bar = bar; this.baz = baz; } getFoo(): number { return this.baz.getBaz() ? this.bar.getBar().length : 42; } } ); const bar = impl<BarComponent, [BazComponent]>( "bar", class BarImpl { private baz: Baz; constructor({ baz }: Mixed<[BazComponent]>) { this.baz = baz; } getBar(): string { return this.baz.getBaz() ? "Hello" : "Bye"; } } ); const baz = impl<BazComponent>( "baz", class BazImpl { getBaz(): boolean { return true; } } ); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); });
src/mixer.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.spec.ts", "retrieved_chunk": " it(\"returns a provider type that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n Impl<FooComponent, [BarComponent, BazComponent]>,\n Provider<\n \"foo\",\n { getFoo: () => number },", "score": 0.9421086311340332 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " });\n});\ndescribe(\"ImplArgs\", () => {\n it(\"returns a tuple that has the same shape of the provider that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n ImplArgs<FooComponent, [BarComponent, BazComponent]>,", "score": 0.9387852549552917 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.9374542236328125 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.9188382625579834 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " it(\"erases all matching component instances before a component with an infinite name\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"x-baz\", { getBaz: () => boolean }>;\n type QuxComponent = Component<\"qux\", { getQux: () => bigint }>;\n type XxxComponent = Component<string, { getXxx: () => number }>;\n type YyyComponent = Component<`x-${string}`, { getYyy: () => number }>;\n assertType<\n Equals<\n Mixed<[FooComponent, XxxComponent, BarComponent, BazComponent, YyyComponent, QuxComponent]>,", "score": 0.9159795641899109 } ]
typescript
foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({
import type { AsString, IsFiniteString, Merge, Prod } from "./utils"; /** * `Component<N, T>` represents a component. * @param N The name of the component. * @param T The type of the component instance. */ export type Component<N extends string, T extends unknown> = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Component"; name: N; type: T; }; /** * The upper bound of component types. */ export type AbstractComponent = Component<string, unknown>; /** * Returns the instance type of a component. * @param C A component. */ export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T> ? _Instance<N, T> : never; type _Instance<N extends string, T extends unknown> = N extends unknown ? IsFiniteString<N> extends true ? { readonly [N0 in N]: T } : { readonly [N0 in N]?: T } : never; /** * Returns the mixed instance type of components. * @param Cs Components. */ export type Mixed<Cs extends AbstractComponent[]>
= Merge<Prod<FilteredInstances<Cs, [], never>>>;
// prettier-ignore type FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, K extends string > = Cs extends [] ? Is : Cs extends [ ...infer Xs extends AbstractComponent[], infer X extends AbstractComponent, ] ? _FilteredInstances<Xs, Is, Instance<X>, K> : []; // prettier-ignore type _FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, I extends {}, K extends string > = I extends unknown ? keyof I extends K ? FilteredInstances<Cs, Is, K> : IsFiniteString<AsString<keyof I>> extends true ? FilteredInstances<Cs, [I, ...Is], K | AsString<keyof I>> : FilteredInstances<Cs, Is, K | AsString<keyof I>> : never;
src/component.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.ts", "retrieved_chunk": " : never;\nexport type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{\n [K in keyof Ps]: ReconstructComponent<Ps[K]>;\n}>;\n/**\n * Returns the provider type that implements a component.\n * @param C A component.\n * @param Ds A list of dependencies.\n */\nexport type Impl<", "score": 0.8623346090316772 }, { "filename": "src/provider.ts", "retrieved_chunk": "import type { AbstractComponent, Component, Mixed } from \"./component\";\n/**\n * `Provider<N, T, D>` represents a component provider.\n * @param N The name of the component.\n * @param T The type of the provided instance.\n * @param D The type of the dependencies.\n */\nexport type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __type: \"hokemi.type.Provider\";", "score": 0.8404147624969482 }, { "filename": "src/provider.ts", "retrieved_chunk": " C extends AbstractComponent,\n Ds extends AbstractComponent[] = [],\n> = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;\nexport type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs<\n Impl<C, Ds>\n>;\ntype _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D>\n ? [name: N, factory: Factory<T, D>]\n : never;\n/**", "score": 0.8335148096084595 }, { "filename": "src/provider.ts", "retrieved_chunk": " * Creates an implementation of a component.\n * @param name The name of the component.\n * @param factory A factory function or class that creates an instance of the component.\n * @returns An implementation (provider) of the component.\n */\nexport function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>(\n ...[name, factory]: ImplArgs<C, Ds>\n): Impl<C, Ds> {\n const provider: AbstractProvider = {\n // eslint-disable-next-line @typescript-eslint/naming-convention", "score": 0.8318537473678589 }, { "filename": "src/provider.ts", "retrieved_chunk": " P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never\n) extends (deps: infer I) => unknown\n ? I\n : never;\nexport type ReconstructComponent<P extends AbstractProvider> = P extends Provider<\n infer N,\n infer T,\n never\n>\n ? Component<N, T>", "score": 0.8253983855247498 } ]
typescript
= Merge<Prod<FilteredInstances<Cs, [], never>>>;
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component } from "./component"; import type { Factory, Impl, ImplArgs, MixedProvidedInstance, Provider, ProviderDependencies, ProviderName, ReconstructComponent, } from "./provider"; import { invokecFactory, impl } from "./provider"; describe("invokecFactory", () => { it("calls the argument if it is a function", () => { type Foo = { getFoo: () => number }; const factory = (foo: number): Foo => ({ getFoo: () => foo }); const value = invokecFactory(factory, 42); assertType<Equals<typeof value, Foo>>(); expect(value.getFoo()).toBe(42); }); it("calls the constructor of the argument if it is a class", () => { const factory = class Foo { private foo: number; constructor(foo: number) { this.foo = foo; } getFoo(): number { return this.foo; } }; const value = invokecFactory(factory, 42); assertType<Equals<typeof value, InstanceType<typeof factory>>>(); expect(value.getFoo()).toBe(42); }); }); describe("ProviderName", () => { it("returns the name of the provider", () => { type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; assertType<Equals<ProviderName<FooProvider>, "foo">>(); }); it("distributes over union members", () => { assertType<Equals<ProviderName<never>, never>>(); type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider< "bar", { getBar: () => string }, { baz: { getBaz: () => boolean } } >; assertType<Equals<ProviderName<FooProvider | BarProvider>, "foo" | "bar">>(); }); }); describe("ProviderDependencies", () => { it("returns the dependencies of the provider", () => { type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; assertType<Equals<ProviderDependencies<FooProvider>, { bar: { getBar: () => string } }>>(); }); it("returns the intersection of the dependencies of all the union members", () => { assertType<Equals<ProviderDependencies<never>, unknown>>(); type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider< "bar", { getBar: () => string }, { baz: { getBaz: () => boolean } } >; assertType< Equals< ProviderDependencies<FooProvider | BarProvider>, { bar: { getBar: () => string } } & { baz: { getBaz: () => boolean } } > >(); }); }); describe("ReconstructComponent", () => { it("reconstructs a component type from the provider type", () => { type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; assertType< Equals<
ReconstructComponent<FooProvider>, Component<"foo", { getFoo: () => number }>> >();
}); it("distributes over union members", () => { assertType<Equals<ReconstructComponent<never>, never>>(); type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider<"bar", { getBar: () => string }, {}>; assertType< Equals< ReconstructComponent<FooProvider | BarProvider>, Component<"foo", { getFoo: () => number }> | Component<"bar", { getBar: () => string }> > >(); }); }); describe("MixedProvidedInstance", () => { it("returns a mixed instance type of the providers", () => { assertType<Equals<MixedProvidedInstance<[]>, {}>>(); type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider<"bar", { getBar: () => string }, {}>; type BazProvider = Provider<"baz", { getBaz: () => boolean }, {}>; assertType< Equals< MixedProvidedInstance<[FooProvider, BarProvider, BazProvider]>, Readonly<{ foo: { getFoo: () => number }; bar: { getBar: () => string }; baz: { getBaz: () => boolean }; }> > >(); type Bar2Provider = Provider<"bar", { getBar2: () => string }, {}>; assertType< Equals< MixedProvidedInstance<[FooProvider, BarProvider, BazProvider, Bar2Provider]>, Readonly<{ foo: { getFoo: () => number }; bar: { getBar2: () => string }; baz: { getBaz: () => boolean }; }> > >(); }); it("distibutes over union members", () => { type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider<"bar", { getBar: () => string }, {}>; type BazProvider = Provider<"baz", { getBaz: () => boolean }, {}>; assertType< Equals< MixedProvidedInstance<[FooProvider, BarProvider] | [BazProvider]>, | Readonly<{ foo: { getFoo: () => number }; bar: { getBar: () => string }; }> | Readonly<{ baz: { getBaz: () => boolean }; }> > >(); }); }); describe("Impl", () => { it("returns a provider type that implements the component", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< Impl<FooComponent, [BarComponent, BazComponent]>, Provider< "foo", { getFoo: () => number }, Readonly<{ bar: { getBar: () => string }; baz: { getBaz: () => boolean }; }> > > >(); }); it("distributes over union members", () => { assertType<Equals<Impl<never, [BazComponent]>, never>>(); type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< Impl<FooComponent | BarComponent, [BazComponent]>, | Provider<"foo", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>> | Provider<"bar", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>> > >(); }); }); describe("ImplArgs", () => { it("returns a tuple that has the same shape of the provider that implements the component", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< ImplArgs<FooComponent, [BarComponent, BazComponent]>, [ "foo", Factory< { getFoo: () => number }, Readonly<{ bar: { getBar: () => string }; baz: { getBaz: () => boolean }; }> >, ] > >(); }); it("distributes over union members", () => { assertType<Equals<ImplArgs<never, [BazComponent]>, never>>(); type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< ImplArgs<FooComponent | BarComponent, [BazComponent]>, | ["foo", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>] | ["bar", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>] > >(); }); }); describe("impl", () => { it("creates a provider that implements a component", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); assertType<Equals<typeof foo, Impl<FooComponent, [BarComponent]>>>(); expect(foo.name).toBe("foo"); const value = invokecFactory(foo.factory, { bar: { getBar: () => "Hello", }, }); expect(value.getFoo()).toBe(5); }); });
src/provider.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.spec.ts", "retrieved_chunk": "import type { Equals } from \"./__tests__/types\";\nimport { assertType } from \"./__tests__/types\";\nimport type { Component, Instance, Mixed } from \"./component\";\ndescribe(\"Instance\", () => {\n it(\"returns an object type with a property whose name is the component name and whose type is the component type\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n assertType<Equals<Instance<FooComponent>, Readonly<{ foo: { getFoo: () => number } }>>>();\n });\n it(\"returns the union type of object types if the component name is a union string\", () => {\n type XxxComponent = Component<never, { getXxx: () => number }>;", "score": 0.9240335822105408 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Equals<\n Instance<FooComponent | BarComponent>,\n Readonly<{ foo: { getFoo: () => number } }> | Readonly<{ bar: { getBar: () => string } }>\n >\n >();\n });\n});\ndescribe(\"Mixed\", () => {\n it(\"returns a mixed instance type of the components\", () => {\n assertType<Equals<Mixed<[]>, {}>>();", "score": 0.9210118055343628 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.9204467535018921 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n qux: { getQux: () => bigint };\n }>\n >\n >();\n });\n it(\"returns an empty object type if the input is not a tuple\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;", "score": 0.9127018451690674 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Instance<YyyComponent>,\n Readonly<{ [key: `x-${string}`]: { getYyy: () => number } | undefined }>\n >\n >();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<Instance<never>, never>>();\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n assertType<", "score": 0.9108203053474426 } ]
typescript
ReconstructComponent<FooProvider>, Component<"foo", { getFoo: () => number }>> >();
import type { AsString, IsFiniteString, Merge, Prod } from "./utils"; /** * `Component<N, T>` represents a component. * @param N The name of the component. * @param T The type of the component instance. */ export type Component<N extends string, T extends unknown> = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Component"; name: N; type: T; }; /** * The upper bound of component types. */ export type AbstractComponent = Component<string, unknown>; /** * Returns the instance type of a component. * @param C A component. */ export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T> ? _Instance<N, T> : never; type _Instance<N extends string, T extends unknown> = N extends unknown ? IsFiniteString<N> extends true ? { readonly [N0 in N]: T } : { readonly [N0 in N]?: T } : never; /** * Returns the mixed instance type of components. * @param Cs Components. */ export type Mixed<Cs extends AbstractComponent[
]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;
// prettier-ignore type FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, K extends string > = Cs extends [] ? Is : Cs extends [ ...infer Xs extends AbstractComponent[], infer X extends AbstractComponent, ] ? _FilteredInstances<Xs, Is, Instance<X>, K> : []; // prettier-ignore type _FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, I extends {}, K extends string > = I extends unknown ? keyof I extends K ? FilteredInstances<Cs, Is, K> : IsFiniteString<AsString<keyof I>> extends true ? FilteredInstances<Cs, [I, ...Is], K | AsString<keyof I>> : FilteredInstances<Cs, Is, K | AsString<keyof I>> : never;
src/component.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.ts", "retrieved_chunk": " : never;\nexport type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{\n [K in keyof Ps]: ReconstructComponent<Ps[K]>;\n}>;\n/**\n * Returns the provider type that implements a component.\n * @param C A component.\n * @param Ds A list of dependencies.\n */\nexport type Impl<", "score": 0.863906979560852 }, { "filename": "src/provider.ts", "retrieved_chunk": "import type { AbstractComponent, Component, Mixed } from \"./component\";\n/**\n * `Provider<N, T, D>` represents a component provider.\n * @param N The name of the component.\n * @param T The type of the provided instance.\n * @param D The type of the dependencies.\n */\nexport type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __type: \"hokemi.type.Provider\";", "score": 0.8413858413696289 }, { "filename": "src/provider.ts", "retrieved_chunk": " C extends AbstractComponent,\n Ds extends AbstractComponent[] = [],\n> = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;\nexport type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs<\n Impl<C, Ds>\n>;\ntype _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D>\n ? [name: N, factory: Factory<T, D>]\n : never;\n/**", "score": 0.8370176553726196 }, { "filename": "src/provider.ts", "retrieved_chunk": " * Creates an implementation of a component.\n * @param name The name of the component.\n * @param factory A factory function or class that creates an instance of the component.\n * @returns An implementation (provider) of the component.\n */\nexport function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>(\n ...[name, factory]: ImplArgs<C, Ds>\n): Impl<C, Ds> {\n const provider: AbstractProvider = {\n // eslint-disable-next-line @typescript-eslint/naming-convention", "score": 0.8318421840667725 }, { "filename": "src/provider.ts", "retrieved_chunk": " P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never\n) extends (deps: infer I) => unknown\n ? I\n : never;\nexport type ReconstructComponent<P extends AbstractProvider> = P extends Provider<\n infer N,\n infer T,\n never\n>\n ? Component<N, T>", "score": 0.8292042016983032 } ]
typescript
]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Mixed } from "./component"; import type { Mixer } from "./mixer"; import { mixer } from "./mixer"; import type { Impl } from "./provider"; import { impl } from "./provider"; describe("Mixer", () => { describe("new", () => { /* eslint-disable @typescript-eslint/naming-convention */ type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("creates an instance if there is no error", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type M = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); it("reports missing dependencies if some dependencies are missing", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M["new"], | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "bar"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); }); it("reports incompatible dependencies if some dependencies are incompatible", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type Bar2 = { getBar2: () => string }; type Bar2Component = Component<"bar", Bar2>; type Bar2Impl = Impl<Bar2Component, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl, BazImpl, Bar2Impl]>; assertType< Equals< M["new"], { __incompatibleDependenciesError?: { reason: "some dependencies are incompatible"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; actualType: Bar2; }, ]; }; } > >(); }); it("reports missing dependencies if some dependencies are possibly missing", () => { type FooImpl = Impl<FooComponent, [BarComponent]>; type BarImpl = Impl<BarComponent>; type BarBazImpl = Impl<BarComponent | BazComponent>; type M1 = Mixer<[FooImpl, BarBazImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarBazImpl, BarImpl]>; assertType< Equals<M2["new"], () => Mixed<[FooComponent, BarComponent | BazComponent, BarComponent]>> >(); }); it("allows creating an instance if any possible combination of dependencies is provided", () => { type FooImpl = Impl<FooComponent, [BarComponent] | [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: | [ { name: "bar"; expectedType: Bar; }, ] | [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType<Equals<M2["new"], () => Mixed<[FooComponent, BarComponent]>>>(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType<Equals<M3["new"], () => Mixed<[FooComponent, BazComponent]>>>(); }); it("reports missing dependencies unless all possible dependencies are provided", () => { type FooImpl = Impl<FooComponent, [BarComponent]> | Impl<FooComponent, [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ | { name: "bar"; expectedType: Bar; } | { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M2["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType< Equals< M3["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M4 = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M4["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); /* eslint-enable @typescript-eslint/naming-convention */ }); }); describe("mixer", () => { type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("mixes components and creates a mixed instance", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); it("overrides previous mixed components", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const baz2 = impl<BazComponent>("baz", () => ({ getBaz: () => false, })); const m = mixer(foo, bar, baz).with(baz2); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz, typeof baz2]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(42); }); it("throws if a component is referenced during its initialization", () => { // foo and bar reference each other during initialization const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", ({ foo }) => ({ getBar: () => foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).toThrow("'foo' is referenced during its initialization"); }); it("does not throw if a component is referenced after its initialization, even if there is a circular dependency", () => { // foo references bar during its initialization, while bar defers referencing foo until it is actually used // (this is not a good example though; it loops forever if you call foo.getFoo() or bar.getBar()) const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("
bar", deps => ({
getBar: () => deps.foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).not.toThrow(); }); it("accepts classes as compoent factories", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>( "foo", class FooImpl { private bar: Bar; private baz: Baz; constructor({ bar, baz }: Mixed<[BarComponent, BazComponent]>) { this.bar = bar; this.baz = baz; } getFoo(): number { return this.baz.getBaz() ? this.bar.getBar().length : 42; } } ); const bar = impl<BarComponent, [BazComponent]>( "bar", class BarImpl { private baz: Baz; constructor({ baz }: Mixed<[BazComponent]>) { this.baz = baz; } getBar(): string { return this.baz.getBaz() ? "Hello" : "Bye"; } } ); const baz = impl<BazComponent>( "baz", class BazImpl { getBaz(): boolean { return true; } } ); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); });
src/mixer.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n qux: { getQux: () => bigint };\n }>\n >\n >();\n });\n it(\"returns an empty object type if the input is not a tuple\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;", "score": 0.8537960648536682 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ProviderName,\n ReconstructComponent,\n} from \"./provider\";\nimport { invokecFactory, impl } from \"./provider\";\ndescribe(\"invokecFactory\", () => {\n it(\"calls the argument if it is a function\", () => {\n type Foo = { getFoo: () => number };\n const factory = (foo: number): Foo => ({ getFoo: () => foo });\n const value = invokecFactory(factory, 42);\n assertType<Equals<typeof value, Foo>>();", "score": 0.8528949022293091 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n baz: { getBaz: () => boolean };\n }>\n >\n >\n >();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<Impl<never, [BazComponent]>, never>>();", "score": 0.8495893478393555 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.8463999032974243 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.8451821804046631 } ]
typescript
bar", deps => ({
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Mixed } from "./component"; import type { Mixer } from "./mixer"; import { mixer } from "./mixer"; import type { Impl } from "./provider"; import { impl } from "./provider"; describe("Mixer", () => { describe("new", () => { /* eslint-disable @typescript-eslint/naming-convention */ type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("creates an instance if there is no error", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type M = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); it("reports missing dependencies if some dependencies are missing", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M["new"], | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "bar"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); }); it("reports incompatible dependencies if some dependencies are incompatible", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type Bar2 = { getBar2: () => string }; type Bar2Component = Component<"bar", Bar2>; type Bar2Impl = Impl<Bar2Component, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl, BazImpl, Bar2Impl]>; assertType< Equals< M["new"], { __incompatibleDependenciesError?: { reason: "some dependencies are incompatible"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; actualType: Bar2; }, ]; }; } > >(); }); it("reports missing dependencies if some dependencies are possibly missing", () => { type FooImpl = Impl<FooComponent, [BarComponent]>; type BarImpl = Impl<BarComponent>; type BarBazImpl = Impl<BarComponent | BazComponent>; type M1 = Mixer<[FooImpl, BarBazImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarBazImpl, BarImpl]>; assertType< Equals<M2["new"], () => Mixed<[FooComponent, BarComponent | BazComponent, BarComponent]>> >(); }); it("allows creating an instance if any possible combination of dependencies is provided", () => { type FooImpl = Impl<FooComponent, [BarComponent] | [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: | [ { name: "bar"; expectedType: Bar; }, ] | [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType<Equals<M2["new"], () => Mixed<[FooComponent, BarComponent]>>>(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType<Equals<M3["new"], () => Mixed<[FooComponent, BazComponent]>>>(); }); it("reports missing dependencies unless all possible dependencies are provided", () => { type FooImpl = Impl<FooComponent, [BarComponent]> | Impl<FooComponent, [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ | { name: "bar"; expectedType: Bar; } | { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M2["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType< Equals< M3["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M4 = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M4["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); /* eslint-enable @typescript-eslint/naming-convention */ }); }); describe("mixer", () => { type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("mixes components and creates a mixed instance", () => { const foo = impl<FooComponent,
[BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({
getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); it("overrides previous mixed components", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const baz2 = impl<BazComponent>("baz", () => ({ getBaz: () => false, })); const m = mixer(foo, bar, baz).with(baz2); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz, typeof baz2]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(42); }); it("throws if a component is referenced during its initialization", () => { // foo and bar reference each other during initialization const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", ({ foo }) => ({ getBar: () => foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).toThrow("'foo' is referenced during its initialization"); }); it("does not throw if a component is referenced after its initialization, even if there is a circular dependency", () => { // foo references bar during its initialization, while bar defers referencing foo until it is actually used // (this is not a good example though; it loops forever if you call foo.getFoo() or bar.getBar()) const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", deps => ({ getBar: () => deps.foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).not.toThrow(); }); it("accepts classes as compoent factories", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>( "foo", class FooImpl { private bar: Bar; private baz: Baz; constructor({ bar, baz }: Mixed<[BarComponent, BazComponent]>) { this.bar = bar; this.baz = baz; } getFoo(): number { return this.baz.getBaz() ? this.bar.getBar().length : 42; } } ); const bar = impl<BarComponent, [BazComponent]>( "bar", class BarImpl { private baz: Baz; constructor({ baz }: Mixed<[BazComponent]>) { this.baz = baz; } getBar(): string { return this.baz.getBaz() ? "Hello" : "Bye"; } } ); const baz = impl<BazComponent>( "baz", class BazImpl { getBaz(): boolean { return true; } } ); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); });
src/mixer.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.spec.ts", "retrieved_chunk": " it(\"returns a provider type that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n Impl<FooComponent, [BarComponent, BazComponent]>,\n Provider<\n \"foo\",\n { getFoo: () => number },", "score": 0.941034734249115 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.9384055137634277 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " });\n});\ndescribe(\"ImplArgs\", () => {\n it(\"returns a tuple that has the same shape of the provider that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n ImplArgs<FooComponent, [BarComponent, BazComponent]>,", "score": 0.938129186630249 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.9186576008796692 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " it(\"erases all matching component instances before a component with an infinite name\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"x-baz\", { getBaz: () => boolean }>;\n type QuxComponent = Component<\"qux\", { getQux: () => bigint }>;\n type XxxComponent = Component<string, { getXxx: () => number }>;\n type YyyComponent = Component<`x-${string}`, { getYyy: () => number }>;\n assertType<\n Equals<\n Mixed<[FooComponent, XxxComponent, BarComponent, BazComponent, YyyComponent, QuxComponent]>,", "score": 0.9153963327407837 } ]
typescript
[BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Instance, Mixed } from "./component"; describe("Instance", () => { it("returns an object type with a property whose name is the component name and whose type is the component type", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; assertType<Equals<Instance<FooComponent>, Readonly<{ foo: { getFoo: () => number } }>>>(); }); it("returns the union type of object types if the component name is a union string", () => { type XxxComponent = Component<never, { getXxx: () => number }>; assertType<Equals<Instance<XxxComponent>, never>>(); type FooComponent = Component<"foo1" | "foo2", { getFoo: () => number }>; assertType< Equals< Instance<FooComponent>, Readonly<{ foo1: { getFoo: () => number } }> | Readonly<{ foo2: { getFoo: () => number } }> > >(); }); it("returns an object type with an optional index signature if the component name is not of a finite string type", () => { type XxxComponent = Component<string, { getXxx: () => number }>; assertType< Equals< Instance<XxxComponent>, Readonly<{ [key: string]: { getXxx: () => number } | undefined }> > >(); type YyyComponent = Component<`x-${string}`, { getYyy: () => number }>; assertType< Equals< Instance<YyyComponent>, Readonly<{ [key: `x-${string}`]: { getYyy: () => number } | undefined }> > >(); }); it("distributes over union members", () => { assertType<Equals<Instance<never>, never>>(); type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; assertType< Equals< Instance<FooComponent | BarComponent>, Readonly<{ foo: { getFoo: () => number } }> | Readonly<{ bar: { getBar: () => string } }> > >(); }); }); describe("Mixed", () => { it("returns a mixed instance type of the components", () => { assertType
<Equals<Mixed<[]>, {}>>();
type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< Mixed<[FooComponent, BarComponent, BazComponent]>, Readonly<{ foo: { getFoo: () => number }; bar: { getBar: () => string }; baz: { getBaz: () => boolean }; }> > >(); }); it("overrides previously declared component instances", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; type Bar2Component = Component<"bar", { getBar2: () => bigint }>; assertType< Equals< Mixed<[FooComponent, BarComponent, BazComponent, Bar2Component]>, Readonly<{ foo: { getFoo: () => number }; bar: { getBar2: () => bigint }; baz: { getBaz: () => boolean }; }> > >(); }); it("erases all matching component instances before a component with an infinite name", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"x-baz", { getBaz: () => boolean }>; type QuxComponent = Component<"qux", { getQux: () => bigint }>; type XxxComponent = Component<string, { getXxx: () => number }>; type YyyComponent = Component<`x-${string}`, { getYyy: () => number }>; assertType< Equals< Mixed<[FooComponent, XxxComponent, BarComponent, BazComponent, YyyComponent, QuxComponent]>, Readonly<{ bar: { getBar: () => string }; qux: { getQux: () => bigint }; }> > >(); }); it("returns an empty object type if the input is not a tuple", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; assertType<Equals<Mixed<FooComponent[]>, {}>>(); assertType<Equals<Mixed<[...FooComponent[], BarComponent]>, {}>>(); assertType<Equals<Mixed<[FooComponent, ...BarComponent[]]>, {}>>(); }); it("distibutes over union members", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< Mixed<[FooComponent, BarComponent] | [BazComponent]>, | Readonly<{ foo: { getFoo: () => number }; bar: { getBar: () => string }; }> | Readonly<{ baz: { getBaz: () => boolean }; }> > >(); }); });
src/component.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.946351170539856 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n baz: { getBaz: () => boolean };\n }>\n >\n >\n >();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<Impl<never, [BazComponent]>, never>>();", "score": 0.9338715672492981 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " >();\n });\n});\ndescribe(\"MixedProvidedInstance\", () => {\n it(\"returns a mixed instance type of the providers\", () => {\n assertType<Equals<MixedProvidedInstance<[]>, {}>>();\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n type BarProvider = Provider<\"bar\", { getBar: () => string }, {}>;\n type BazProvider = Provider<\"baz\", { getBaz: () => boolean }, {}>;\n assertType<", "score": 0.9243773818016052 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " >\n >();\n });\n});\ndescribe(\"ReconstructComponent\", () => {\n it(\"reconstructs a component type from the provider type\", () => {\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n assertType<\n Equals<ReconstructComponent<FooProvider>, Component<\"foo\", { getFoo: () => number }>>\n >();", "score": 0.9198639392852783 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " assertType<Equals<ProviderName<FooProvider>, \"foo\">>();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<ProviderName<never>, never>>();\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n type BarProvider = Provider<\n \"bar\",\n { getBar: () => string },\n { baz: { getBaz: () => boolean } }\n >;", "score": 0.9180810451507568 } ]
typescript
<Equals<Mixed<[]>, {}>>();
import type { AsString, IsFiniteString, Merge, Prod } from "./utils"; /** * `Component<N, T>` represents a component. * @param N The name of the component. * @param T The type of the component instance. */ export type Component<N extends string, T extends unknown> = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Component"; name: N; type: T; }; /** * The upper bound of component types. */ export type AbstractComponent = Component<string, unknown>; /** * Returns the instance type of a component. * @param C A component. */ export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T> ? _Instance<N, T> : never; type _Instance<N extends string, T extends unknown> = N extends unknown ? IsFiniteString<N> extends true ? { readonly [N0 in N]: T } : { readonly [N0 in N]?: T } : never; /** * Returns the mixed instance type of components. * @param Cs Components. */
export type Mixed<Cs extends AbstractComponent[]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;
// prettier-ignore type FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, K extends string > = Cs extends [] ? Is : Cs extends [ ...infer Xs extends AbstractComponent[], infer X extends AbstractComponent, ] ? _FilteredInstances<Xs, Is, Instance<X>, K> : []; // prettier-ignore type _FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, I extends {}, K extends string > = I extends unknown ? keyof I extends K ? FilteredInstances<Cs, Is, K> : IsFiniteString<AsString<keyof I>> extends true ? FilteredInstances<Cs, [I, ...Is], K | AsString<keyof I>> : FilteredInstances<Cs, Is, K | AsString<keyof I>> : never;
src/component.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.ts", "retrieved_chunk": " : never;\nexport type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{\n [K in keyof Ps]: ReconstructComponent<Ps[K]>;\n}>;\n/**\n * Returns the provider type that implements a component.\n * @param C A component.\n * @param Ds A list of dependencies.\n */\nexport type Impl<", "score": 0.8523403406143188 }, { "filename": "src/provider.ts", "retrieved_chunk": "import type { AbstractComponent, Component, Mixed } from \"./component\";\n/**\n * `Provider<N, T, D>` represents a component provider.\n * @param N The name of the component.\n * @param T The type of the provided instance.\n * @param D The type of the dependencies.\n */\nexport type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __type: \"hokemi.type.Provider\";", "score": 0.8439170122146606 }, { "filename": "src/provider.ts", "retrieved_chunk": " C extends AbstractComponent,\n Ds extends AbstractComponent[] = [],\n> = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;\nexport type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs<\n Impl<C, Ds>\n>;\ntype _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D>\n ? [name: N, factory: Factory<T, D>]\n : never;\n/**", "score": 0.8380119204521179 }, { "filename": "src/provider.ts", "retrieved_chunk": " P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never\n) extends (deps: infer I) => unknown\n ? I\n : never;\nexport type ReconstructComponent<P extends AbstractProvider> = P extends Provider<\n infer N,\n infer T,\n never\n>\n ? Component<N, T>", "score": 0.8365678787231445 }, { "filename": "src/provider.ts", "retrieved_chunk": " * Creates an implementation of a component.\n * @param name The name of the component.\n * @param factory A factory function or class that creates an instance of the component.\n * @returns An implementation (provider) of the component.\n */\nexport function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>(\n ...[name, factory]: ImplArgs<C, Ds>\n): Impl<C, Ds> {\n const provider: AbstractProvider = {\n // eslint-disable-next-line @typescript-eslint/naming-convention", "score": 0.8350546360015869 } ]
typescript
export type Mixed<Cs extends AbstractComponent[]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;
import { request } from "../util/request.util"; import { AppConf } from "../app-conf"; export type GithubIssue = { title: string; body: string; }; export interface GithubIssueResponse { url: string; repository_url: string; labels_url: string; comments_url: string; events_url: string; html_url: string; id: number; node_id: string; number: number; title: string; user: User; labels: any[]; state: string; locked: boolean; assignee: null; assignees: any[]; milestone: null; comments: number; created_at: Date; updated_at: Date; closed_at: null; author_association: string; active_lock_reason: null; body: string; closed_by: null; reactions: Reactions; timeline_url: string; performed_via_github_app: null; state_reason: null; } export interface Reactions { url: string; total_count: number; "+1": number; "-1": number; laugh: number; hooray: number; confused: number; heart: number; rocket: number; eyes: number; } export interface User { login: string; id: number; node_id: string; avatar_url: string; gravatar_id: string; url: string; html_url: string; followers_url: string; following_url: string; gists_url: string; starred_url: string; subscriptions_url: string; organizations_url: string; repos_url: string; events_url: string; received_events_url: string; type: string; site_admin: boolean; } export async function createIssue( repo: string, issue: GithubIssue ): Promise<GithubIssueResponse> { return ( await request({ name: "Create Github Issue",
url: `${AppConf.githubApiBaseUrl}/repos/${repo}/issues`, method: "POST", headers: {
"Content-Type": "application/json", "X-GitHub-Api-Version": "2022-11-28", Authorization: `Bearer ${AppConf.githubAuthKey}`, Accept: "application/vnd.github+json", }, body: issue, }) ).json(); }
src/api/dao/github.dao.ts
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": " * @param chapter The chapter to get the icon for.\n */\nexport async function getChapterIcon(chapter: string): Promise<ArrayBuffer> {\n return await (\n await request({\n name: \"Chapter Icon\",\n url: `${AppConf.settingsBaseUrl}/chapter-icons/${chapter}.png`,\n method: \"GET\",\n })\n ).arrayBuffer();", "score": 0.7664694786071777 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " const finalQuery = formQuery(chapters);\n const response = await request({\n name: \"Meetup Event\",\n url: `${AppConf.meetupApiBaseUrl}/gql`,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: { query: finalQuery },\n });\n return processResponse((await response.json()) as QueryResponse);\n}", "score": 0.7376479506492615 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": " })\n ) +\n \"\\n\"\n );\n let response;\n try {\n response = await fetch(options.url, {\n method: options.method,\n headers: options.headers,\n body: JSON.stringify(options.body),", "score": 0.7086039781570435 }, { "filename": "src/ui/calendar/coffee.dao.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nimport { WebConf } from \"../web-conf\";\n/**\n * Get the details of all events from the Code and Coffee service.\n */\nexport async function getEvents(): Promise<EventsResponse> {\n const response = await fetch(`${WebConf.rootHost}/info/events`, {\n method: \"GET\",\n });\n return response.json();", "score": 0.7051467299461365 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": "}\n/**\n * Get all the notification settings.\n */\nexport async function getNotificationSettings(): Promise<\n Array<NotificationSetting>\n> {\n return await (\n await request({\n name: \"Notification Settings\",", "score": 0.6844351291656494 } ]
typescript
url: `${AppConf.githubApiBaseUrl}/repos/${repo}/issues`, method: "POST", headers: {
import React, { useEffect, useState } from "react"; import { CoffeeEvent } from "./coffee-event"; import styled from "styled-components"; import { getEvents } from "./coffee.dao"; import { EventStats, getEventStats } from "./events.util"; import { CoffeeEventStats } from "./coffee-event-stats"; const CalendarContainer = styled.div` display: flex; flex-direction: column; height: ${({ height }: { height: number }) => height}px; padding: 15px; border-radius: 20px; box-shadow: 3px 3px 33px rgba(0, 0, 0, 0.04); @media (max-width: 600px) { padding: 0; } `; const EventTitle = styled.h1` @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap"); font-family: "Cormorant Garamond", serif; font-weight: 700; font-size: 36px; margin: 0 0 10px 0; `; const EventHolder = styled.div` border-top: 1px solid #dcdcdc; border-bottom: 1px solid #dcdcdc; overflow-y: scroll; padding-right: 20px; display: flex; flex-direction: column; align-items: center; /* width */ ::-webkit-scrollbar { width: 10px; transform: rotate(180deg); } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d4b9ff; border: 1px solid black; border-radius: 2px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #dbc4ff; border: 2px solid black; border-radius: 2px; } `; export function CoffeeCalendar({ height }: { height: number }) { const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>); const [showStats, setShowStats] = useState(false as boolean); const [stats, setStats
] = useState(undefined as undefined | EventStats);
useEffect(() => { getEvents().then((events) => { const newCoffeeEvents = [] as Array<JSX.Element>; for (const event of events) { if (event) { newCoffeeEvents.push(<CoffeeEvent event={event} key={event.id} />); } } setCoffeeEvents(newCoffeeEvents); setStats(getEventStats(events)); }); }, []); useEffect(() => { function displayDialogListener(event: KeyboardEvent): void { if (event.code === "KeyI" && event.ctrlKey) { setShowStats(!showStats); } } document.addEventListener("keydown", displayDialogListener); return () => { document.removeEventListener("keydown", displayDialogListener); }; }, [showStats]); return ( <CalendarContainer height={height}> <EventTitle>Events</EventTitle> {showStats && stats && <CoffeeEventStats stats={stats} />} <EventHolder>{coffeeEvents}</EventHolder> </CalendarContainer> ); }
src/ui/calendar/coffee-calendar.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": "const EVENT_DESCRIPTION_LENGTH = 125;\nexport function CoffeeEvent({ event }: { event: MeetupEvent }) {\n const [iconImage, setIconImage] = useState(\n undefined as undefined | ReactNode\n );\n const [smallIconImage, setSmallIconImage] = useState(\n undefined as undefined | ReactNode\n );\n function rsvpAction() {\n window.open(event.eventUrl, \"_blank\");", "score": 0.8252565860748291 }, { "filename": "src/ui/wc.util.tsx", "retrieved_chunk": "import { createRoot, Root } from \"react-dom/client\";\nimport { StyleSheetManager } from \"styled-components\";\nimport React from \"react\";\nexport function registerReactWebComponent({\n name,\n Component,\n attributes = [],\n}: {\n name: string;\n Component: any;", "score": 0.753140926361084 }, { "filename": "src/api/dao/email.dao.ts", "retrieved_chunk": "import { request } from \"../util/request.util\";\nimport { AppConf } from \"../app-conf\";\nexport type EmailContent = {\n recipient: string | Array<string>;\n subject: string;\n body: string;\n};\nexport async function sendEmail(email: EmailContent) {\n await request({\n name: \"Send Email\",", "score": 0.73970627784729 }, { "filename": "src/ui/calendar/coffee.dao.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nimport { WebConf } from \"../web-conf\";\n/**\n * Get the details of all events from the Code and Coffee service.\n */\nexport async function getEvents(): Promise<EventsResponse> {\n const response = await fetch(`${WebConf.rootHost}/info/events`, {\n method: \"GET\",\n });\n return response.json();", "score": 0.7377283573150635 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": "import { request } from \"../util/request.util\";\nimport { AppConf } from \"../app-conf\";\n/**\n * The info for a Code and Coffee Chapter.\n */\nexport type Chapter = {\n name: string;\n meetupGroupUrlName: string;\n};\nexport type NotificationSetting = {", "score": 0.7361335754394531 } ]
typescript
] = useState(undefined as undefined | EventStats);
import React, { useEffect, useState } from "react"; import { CoffeeEvent } from "./coffee-event"; import styled from "styled-components"; import { getEvents } from "./coffee.dao"; import { EventStats, getEventStats } from "./events.util"; import { CoffeeEventStats } from "./coffee-event-stats"; const CalendarContainer = styled.div` display: flex; flex-direction: column; height: ${({ height }: { height: number }) => height}px; padding: 15px; border-radius: 20px; box-shadow: 3px 3px 33px rgba(0, 0, 0, 0.04); @media (max-width: 600px) { padding: 0; } `; const EventTitle = styled.h1` @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap"); font-family: "Cormorant Garamond", serif; font-weight: 700; font-size: 36px; margin: 0 0 10px 0; `; const EventHolder = styled.div` border-top: 1px solid #dcdcdc; border-bottom: 1px solid #dcdcdc; overflow-y: scroll; padding-right: 20px; display: flex; flex-direction: column; align-items: center; /* width */ ::-webkit-scrollbar { width: 10px; transform: rotate(180deg); } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d4b9ff; border: 1px solid black; border-radius: 2px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #dbc4ff; border: 2px solid black; border-radius: 2px; } `; export function CoffeeCalendar({ height }: { height: number }) { const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>); const [showStats, setShowStats] = useState(false as boolean); const [stats, setStats] = useState(undefined as undefined | EventStats); useEffect(() => { getEvents(
).then((events) => {
const newCoffeeEvents = [] as Array<JSX.Element>; for (const event of events) { if (event) { newCoffeeEvents.push(<CoffeeEvent event={event} key={event.id} />); } } setCoffeeEvents(newCoffeeEvents); setStats(getEventStats(events)); }); }, []); useEffect(() => { function displayDialogListener(event: KeyboardEvent): void { if (event.code === "KeyI" && event.ctrlKey) { setShowStats(!showStats); } } document.addEventListener("keydown", displayDialogListener); return () => { document.removeEventListener("keydown", displayDialogListener); }; }, [showStats]); return ( <CalendarContainer height={height}> <EventTitle>Events</EventTitle> {showStats && stats && <CoffeeEventStats stats={stats} />} <EventHolder>{coffeeEvents}</EventHolder> </CalendarContainer> ); }
src/ui/calendar/coffee-calendar.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": "const EVENT_DESCRIPTION_LENGTH = 125;\nexport function CoffeeEvent({ event }: { event: MeetupEvent }) {\n const [iconImage, setIconImage] = useState(\n undefined as undefined | ReactNode\n );\n const [smallIconImage, setSmallIconImage] = useState(\n undefined as undefined | ReactNode\n );\n function rsvpAction() {\n window.open(event.eventUrl, \"_blank\");", "score": 0.8452638983726501 }, { "filename": "src/ui/wc.util.tsx", "retrieved_chunk": "import { createRoot, Root } from \"react-dom/client\";\nimport { StyleSheetManager } from \"styled-components\";\nimport React from \"react\";\nexport function registerReactWebComponent({\n name,\n Component,\n attributes = [],\n}: {\n name: string;\n Component: any;", "score": 0.7457833886146545 }, { "filename": "src/api/service/events.service.ts", "retrieved_chunk": "import { getMeetupEvents, MeetupEvent } from \"../dao/meetup.dao\";\nimport { getChapters } from \"../dao/settings.dao\";\n/**\n * Get a list of all upcoming events for Code and Coffee.\n */\nexport async function getEvents(): Promise<Array<MeetupEvent>> {\n const chapters = await getChapters();\n const events = await getMeetupEvents(chapters);\n return events.sort((a, b) => {\n return new Date(a.dateTime).getTime() - new Date(b.dateTime).getTime();", "score": 0.7357277870178223 }, { "filename": "src/ui/calendar/coffee.dao.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nimport { WebConf } from \"../web-conf\";\n/**\n * Get the details of all events from the Code and Coffee service.\n */\nexport async function getEvents(): Promise<EventsResponse> {\n const response = await fetch(`${WebConf.rootHost}/info/events`, {\n method: \"GET\",\n });\n return response.json();", "score": 0.7355137467384338 }, { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": " */\nexport function getEventStats(events: EventsResponse): EventStats {\n const result: EventStats = {\n totalEvents: 0,\n totalActiveChapters: 0,\n totalRSVPs: 0,\n };\n const chapters = new Set<string>();\n events.forEach((event) => {\n result.totalEvents++;", "score": 0.7212816476821899 } ]
typescript
).then((events) => {
import { APIGatewayProxyEventV2 } from "aws-lambda"; import { APIGatewayProxyStructuredResultV2 } from "aws-lambda/trigger/api-gateway-proxy"; import { MeetupEvent } from "./dao/meetup.dao"; import { AppConf } from "./app-conf"; import { Controller, routes } from "./routes"; import colors from "colors"; export type EventsResponse = Array<MeetupEvent>; export async function handler( event: APIGatewayProxyEventV2 ): Promise<APIGatewayProxyStructuredResultV2> { try { return await handleRequest(event); } catch (e) { console.error(`Internal server error: ${e}`); return { statusCode: 500, body: JSON.stringify({ message: "Internal server error", requestId: event.requestContext.requestId, }), headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, }; } } async function handleRequest( event: APIGatewayProxyEventV2 ): Promise<APIGatewayProxyStructuredResultV2> { console.log("request received"); if (!isApiKeyValid(event)) { return { statusCode: 401, body: JSON.stringify({ message: "Unauthorized", }), headers: { "Content-Type": "application/json", }, }; } const path = event.requestContext.http.path; const method = event.requestContext.http.method.toUpperCase();
let controller = undefined as undefined | Controller;
for (const route of routes) { if (method === route.method && new RegExp(`^${route.path}$`).test(path)) { controller = route.controller; break; } } if (controller) { const response = await controller(event); if (!response.headers) { response.headers = {}; } response.headers["Access-Control-Allow-Origin"] = "*"; return response; } console.log( colors.blue("No controller found for path ") + colors.yellow(`"${path}"`) ); return { statusCode: 404, body: JSON.stringify({ message: "Not found", requestId: event.requestContext.requestId, }), headers: { "Content-Type": "application/json", }, }; } const API_KEY_PATH = /^\/api\/.*/; /** * Checks if an API key is needed, and if so, if it is valid. API Keys are required for all non cached requests. * @param request The request to validate. */ function isApiKeyValid(request: APIGatewayProxyEventV2): boolean { if (API_KEY_PATH.test(request.requestContext.http.path)) { return request.headers?.["x-api-key"] === AppConf.apiKey; } return true; }
src/api/index.ts
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": " await getChapterIcon(extractChapter(event.rawPath))\n ).toString(\"base64\"),\n headers: {\n \"Content-Type\": \"image/png\",\n },\n isBase64Encoded: true,\n };\n } catch (e: any | Response) {\n if (e.status === 404) {\n return {", "score": 0.8302847146987915 }, { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": " statusCode: 404,\n body: \"Not Found\",\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n };\n } else {\n throw e;\n }\n }", "score": 0.7929565906524658 }, { "filename": "src/api/controllers/notify.controller.ts", "retrieved_chunk": " return {\n statusCode: 400,\n body: JSON.stringify({\n result: \"INVALID_NOTIFICATION\",\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n };\n } else {", "score": 0.788282036781311 }, { "filename": "src/api/controllers/notify.controller.ts", "retrieved_chunk": " return {\n statusCode: 500,\n body: JSON.stringify({\n result: \"FAILURE\",\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n };\n }", "score": 0.7880733013153076 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": " })\n ) +\n \"\\n\"\n );\n let response;\n try {\n response = await fetch(options.url, {\n method: options.method,\n headers: options.headers,\n body: JSON.stringify(options.body),", "score": 0.778401255607605 } ]
typescript
let controller = undefined as undefined | Controller;
import React, { useEffect, useState } from "react"; import { CoffeeEvent } from "./coffee-event"; import styled from "styled-components"; import { getEvents } from "./coffee.dao"; import { EventStats, getEventStats } from "./events.util"; import { CoffeeEventStats } from "./coffee-event-stats"; const CalendarContainer = styled.div` display: flex; flex-direction: column; height: ${({ height }: { height: number }) => height}px; padding: 15px; border-radius: 20px; box-shadow: 3px 3px 33px rgba(0, 0, 0, 0.04); @media (max-width: 600px) { padding: 0; } `; const EventTitle = styled.h1` @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap"); font-family: "Cormorant Garamond", serif; font-weight: 700; font-size: 36px; margin: 0 0 10px 0; `; const EventHolder = styled.div` border-top: 1px solid #dcdcdc; border-bottom: 1px solid #dcdcdc; overflow-y: scroll; padding-right: 20px; display: flex; flex-direction: column; align-items: center; /* width */ ::-webkit-scrollbar { width: 10px; transform: rotate(180deg); } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d4b9ff; border: 1px solid black; border-radius: 2px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #dbc4ff; border: 2px solid black; border-radius: 2px; } `; export function CoffeeCalendar({ height }: { height: number }) { const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>); const [showStats, setShowStats] = useState(false as boolean); const [stats, setStats] = useState(undefined as undefined | EventStats); useEffect(() => { getEvents().then((events) => { const newCoffeeEvents = [] as Array<JSX.Element>; for (const event of events) { if (event) {
newCoffeeEvents.push(<CoffeeEvent event={event} key={event.id} />);
} } setCoffeeEvents(newCoffeeEvents); setStats(getEventStats(events)); }); }, []); useEffect(() => { function displayDialogListener(event: KeyboardEvent): void { if (event.code === "KeyI" && event.ctrlKey) { setShowStats(!showStats); } } document.addEventListener("keydown", displayDialogListener); return () => { document.removeEventListener("keydown", displayDialogListener); }; }, [showStats]); return ( <CalendarContainer height={height}> <EventTitle>Events</EventTitle> {showStats && stats && <CoffeeEventStats stats={stats} />} <EventHolder>{coffeeEvents}</EventHolder> </CalendarContainer> ); }
src/ui/calendar/coffee-calendar.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": "const EVENT_DESCRIPTION_LENGTH = 125;\nexport function CoffeeEvent({ event }: { event: MeetupEvent }) {\n const [iconImage, setIconImage] = useState(\n undefined as undefined | ReactNode\n );\n const [smallIconImage, setSmallIconImage] = useState(\n undefined as undefined | ReactNode\n );\n function rsvpAction() {\n window.open(event.eventUrl, \"_blank\");", "score": 0.82819664478302 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " * @param response The response from the query.\n */\nfunction processResponse(response: QueryResponse): Array<MeetupEvent> {\n const result = [] as Array<MeetupEvent>;\n for (const group of Object.values(response.data)) {\n if (group) {\n for (const event of group.upcomingEvents.edges) {\n result.push(event.node);\n }\n }", "score": 0.759798526763916 }, { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": " */\nexport function getEventStats(events: EventsResponse): EventStats {\n const result: EventStats = {\n totalEvents: 0,\n totalActiveChapters: 0,\n totalRSVPs: 0,\n };\n const chapters = new Set<string>();\n events.forEach((event) => {\n result.totalEvents++;", "score": 0.7551589012145996 }, { "filename": "src/api/service/events.service.ts", "retrieved_chunk": "import { getMeetupEvents, MeetupEvent } from \"../dao/meetup.dao\";\nimport { getChapters } from \"../dao/settings.dao\";\n/**\n * Get a list of all upcoming events for Code and Coffee.\n */\nexport async function getEvents(): Promise<Array<MeetupEvent>> {\n const chapters = await getChapters();\n const events = await getMeetupEvents(chapters);\n return events.sort((a, b) => {\n return new Date(a.dateTime).getTime() - new Date(b.dateTime).getTime();", "score": 0.751166045665741 }, { "filename": "src/ui/wc.util.tsx", "retrieved_chunk": " connectedCallback() {\n const attrs = attributes.reduce(\n (acc, key) =>\n Object.assign(acc, {\n [key]: this.getAttribute(key) ?? undefined,\n }),\n {}\n );\n this.root.render(\n <StyleSheetManager target={this.shadow}>", "score": 0.7472721934318542 } ]
typescript
newCoffeeEvents.push(<CoffeeEvent event={event} key={event.id} />);
import { APIGatewayProxyEventV2 } from "aws-lambda"; import { APIGatewayProxyStructuredResultV2 } from "aws-lambda/trigger/api-gateway-proxy"; import { MeetupEvent } from "./dao/meetup.dao"; import { AppConf } from "./app-conf"; import { Controller, routes } from "./routes"; import colors from "colors"; export type EventsResponse = Array<MeetupEvent>; export async function handler( event: APIGatewayProxyEventV2 ): Promise<APIGatewayProxyStructuredResultV2> { try { return await handleRequest(event); } catch (e) { console.error(`Internal server error: ${e}`); return { statusCode: 500, body: JSON.stringify({ message: "Internal server error", requestId: event.requestContext.requestId, }), headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, }; } } async function handleRequest( event: APIGatewayProxyEventV2 ): Promise<APIGatewayProxyStructuredResultV2> { console.log("request received"); if (!isApiKeyValid(event)) { return { statusCode: 401, body: JSON.stringify({ message: "Unauthorized", }), headers: { "Content-Type": "application/json", }, }; } const path = event.requestContext.http.path; const method = event.requestContext.http.method.toUpperCase(); let controller = undefined as undefined | Controller; for (const route of routes) { if (method === route.method && new RegExp(`^${route.path}$`).test(path)) { controller = route.controller; break; } } if (controller) { const response = await controller(event); if (!response.headers) { response.headers = {}; } response.headers["Access-Control-Allow-Origin"] = "*"; return response; } console.log( colors.blue("No controller found for path ") + colors.yellow(`"${path}"`) ); return { statusCode: 404, body: JSON.stringify({ message: "Not found", requestId: event.requestContext.requestId, }), headers: { "Content-Type": "application/json", }, }; } const API_KEY_PATH = /^\/api\/.*/; /** * Checks if an API key is needed, and if so, if it is valid. API Keys are required for all non cached requests. * @param request The request to validate. */ function isApiKeyValid(request: APIGatewayProxyEventV2): boolean { if (API_KEY_PATH.test(request.requestContext.http.path)) {
return request.headers?.["x-api-key"] === AppConf.apiKey;
} return true; }
src/api/index.ts
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee.dao.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nimport { WebConf } from \"../web-conf\";\n/**\n * Get the details of all events from the Code and Coffee service.\n */\nexport async function getEvents(): Promise<EventsResponse> {\n const response = await fetch(`${WebConf.rootHost}/info/events`, {\n method: \"GET\",\n });\n return response.json();", "score": 0.7522938251495361 }, { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": "}\nconst chapterRegex = /(?<=\\/info\\/chapter-icons\\/).*$/;\nfunction extractChapter(path: string): string {\n const results = path.match(chapterRegex);\n if (results === null) {\n throw new Error(`Could not extract chapter from path ${path}`);\n }\n return results[0];\n}", "score": 0.7348400354385376 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": " })\n ) +\n \"\\n\"\n );\n let response;\n try {\n response = await fetch(options.url, {\n method: options.method,\n headers: options.headers,\n body: JSON.stringify(options.body),", "score": 0.7303392887115479 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": "import colors from \"colors\";\nexport type RequestOptions = {\n name: string;\n url: string;\n body?: any;\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n headers?: Record<string, string>;\n};\nexport async function request(options: RequestOptions): Promise<Response> {\n console.info(", "score": 0.7286238670349121 }, { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": " await getChapterIcon(extractChapter(event.rawPath))\n ).toString(\"base64\"),\n headers: {\n \"Content-Type\": \"image/png\",\n },\n isBase64Encoded: true,\n };\n } catch (e: any | Response) {\n if (e.status === 404) {\n return {", "score": 0.72452712059021 } ]
typescript
return request.headers?.["x-api-key"] === AppConf.apiKey;
import { forwardRef, useMemo, useCallback, useRef, useState, useEffect, Fragment, KeyboardEvent, } from 'react' import { RatingItem } from './RatingItem' import { getDynamicCssVars } from './getDynamicCssVars' import { getGroupClassNames } from './getGroupClassNames' import { getActiveClassNames } from './getActiveClassNames' import { getHFClassNames } from './getHFClassNames' import { getStaticCssVars } from './getStaticCssVars' import { getColors } from './getColors' import { getTabIndex } from './getTabIndex' import { getErrors } from './getErrors' import { getIntersectionIndex, getNumber, getRadioTestIds, getSvgTestIds, devTestId, getResetTestId, isGraphicalValueInteger, isRTLDir, useIsomorphicLayoutEffect, noop, } from './utils' import { Sizes, OrientationProps, TransitionProps, HFProps, RatingClasses } from './constants' import { defaultItemStyles } from './defaultItemStyles' import { RatingProps, Rating as RatingComponent } from './exportedTypes' import { StylesState, RequireAtLeastOne, ValidArrayColors, TabIndex, RatingItemProps, MouseEvent, FocusEvent, HTMLProps, MutableRef, } from './internalTypes' /** Thank you for using **React Rating**. * Visit https://github.com/smastrom/react-rating to read the full documentation. */ export const Rating: typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>( ( { value, items = 5, readOnly = false, onChange = noop, onHoverChange = noop, onFocus = noop, onBlur = noop, isDisabled = false, highlightOnlySelected = false, orientation = OrientationProps.HORIZONTAL, spaceBetween = Sizes.NONE, spaceInside = Sizes.SMALL, radius = Sizes.NONE, transition = TransitionProps.COLORS, itemStyles = defaultItemStyles, isRequired = false, halfFillMode = HFProps.SVG, visibleLabelId, visibleItemLabelIds, invisibleItemLabels, invisibleLabel = readOnly ? value > 0 ? `Rated ${value} on ${items}` : 'Not rated' : 'Rating Selection', resetLabel = 'Reset rating', id, className, style, }, externalRef ) => { /* Helpers */ const ratingValues = Array.from({ length: items }, (_, index) => index + 1) const hasPrecision = readOnly && !Number.isInteger(value) const isEligibleForHF = hasPrecision && !highlightOnlySelected const isNotEligibleForHF = hasPrecision && highlightOnlySelected const ratingValue = isNotEligibleForHF ? Math.round(value) : value const isDynamic = !readOnly && !isDisabled const needsDynamicCssVars = ratingValue >= 0.25 const userClassNames = typeof className === 'string' ? className : '' const absoluteHFMode = halfFillMode === HFProps.BOX ? HFProps.BOX : HFProps.SVG const deservesHF = isEligibleForHF && !isGraphicalValueInteger(ratingValue) const shouldRenderReset = !isRequired && !readOnly const tabIndexItems = isRequired ? items : items + 1 const activeStarIndex = isEligibleForHF ? getIntersectionIndex(ratingValues, ratingValue) : ratingValues.indexOf(ratingValue) /* Deps/Callbacks */ const { staticColors, arrayColors, itemShapes, absoluteStrokeWidth, absoluteBoxBorderWidth } = useMemo(() => { const { itemShapes, itemStrokeWidth, boxBorderWidth, ...colors } = itemStyles const userColors = getColors(colors) return { itemShapes, absoluteStrokeWidth: getNumber(itemStrokeWidth), absoluteBoxBorderWidth: getNumber(boxBorderWidth), ...userColors, } }, [itemStyles]) const hasArrayColors = Object.keys(arrayColors).length > 0 const getDynamicStyles = useCallback( (starIndex: number, shouldGetCssVars: boolean) => ({ dynamicClassNames: deservesHF ? getHFClassNames(ratingValue, items, absoluteHFMode) : getActiveClassNames(highlightOnlySelected, items, starIndex), dynamicCssVars: shouldGetCssVars && hasArrayColors ? getDynamicCssVars( arrayColors as RequireAtLeastOne<ValidArrayColors>, starIndex, highlightOnlySelected ) : [], }), [ arrayColors, hasArrayColors, highlightOnlySelected, absoluteHFMode, deservesHF, items, ratingValue, ] ) const saveTabIndex = useCallback( () => setTabIndex(getTabIndex(tabIndexItems, activeStarIndex, !isRequired)), [activeStarIndex, tabIndexItems, isRequired] ) /* Refs */ const skipStylesMount = useRef(true) const skipTabMount = useRef(true) const wrapperRef = useRef<HTMLDivElement>(null) const radioRefs = useRef<HTMLDivElement[]>([]) const isRTL = useRef(false) /* State */ const [styles, setStyles] = useState<StylesState>({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) const [tabIndex, setTabIndex] = useState<TabIndex[]>(() => { if (isDynamic) { return getTabIndex(tabIndexItems, activeStarIndex, !isRequired) } return [] }) /* Effects */ useIsomorphicLayoutEffect(() => { if (isDynamic && radioRefs.current) { isRTL.current = isRTLDir(radioRefs.current[0]) } }, [isDynamic]) useEffect(() => { if (!skipStylesMount.current) { return setStyles({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } skipStylesMount.current = false }, [ staticColors, getDynamicStyles, absoluteBoxBorderWidth, activeStarIndex, needsDynamicCssVars, ]) useEffect(() => { if (!skipTabMount.current && isDynamic) { return saveTabIndex() } skipTabMount.current = false }, [isDynamic, saveTabIndex]) /* Log critical errors, return null */ const {
shouldRender, reason } = getErrors({
items, itemShapes, }) if (!shouldRender) { console.error(reason) return null } /* Event Handlers */ function handleWhenNeeded( event: FocusEvent | MouseEvent, fromOutsideCallback: () => void, // eslint-disable-next-line @typescript-eslint/no-empty-function fromInsideCallback: () => void = () => {} ) { const fromInside = radioRefs.current.some((radio) => radio === event.relatedTarget) if (!fromInside) { fromOutsideCallback() } else { fromInsideCallback() } } function handleStarLeave() { onHoverChange(0) saveTabIndex() } function handleStarClick(event: MouseEvent, clickedIndex: number) { event.stopPropagation() if (!isRequired && activeStarIndex === clickedIndex) { onChange(0) } else { onChange(clickedIndex + 1) } } function handleMouseEnter(starIndex: number) { onHoverChange(starIndex + 1) setStyles({ ...styles, ...getDynamicStyles(starIndex, true) }) } function handleMouseLeave(event: MouseEvent) { handleWhenNeeded(event, () => { handleStarLeave() }) setStyles({ ...styles, ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } function handleBlur(event: FocusEvent) { handleWhenNeeded(event, () => { handleStarLeave() onBlur() }) } function handleFocus(event: FocusEvent, childIndex: number) { const isResetBtn = !isRequired && childIndex === ratingValues.length const hoveredValue = isResetBtn ? 0 : childIndex + 1 handleWhenNeeded( event, () => { onFocus() onHoverChange(hoveredValue) }, () => { onHoverChange(hoveredValue) } ) } /* Keyboard */ function handleArrowNav(siblingToFocus: number) { setTabIndex(getTabIndex(tabIndexItems, siblingToFocus, !isRequired)) radioRefs.current[siblingToFocus].focus() } function handleKeyDown(event: KeyboardEvent<HTMLDivElement>, childIndex: number) { let siblingToFocus = 0 const lastSibling = isRequired ? ratingValues.length - 1 : ratingValues.length const prevSibling = childIndex - 1 const nextSibling = childIndex + 1 const isResetBtn = !isRequired && childIndex === ratingValues.length const isFiringFromLast = lastSibling === childIndex const isFiringFromFirst = childIndex === 0 const prevToFocus = isFiringFromFirst ? lastSibling : prevSibling const nextToFocus = isFiringFromLast ? 0 : nextSibling switch (event.code) { case 'Shift': case 'Tab': return true case 'ArrowDown': case 'ArrowRight': siblingToFocus = !isRTL.current ? nextToFocus : prevToFocus return handleArrowNav(siblingToFocus) case 'ArrowUp': case 'ArrowLeft': siblingToFocus = !isRTL.current ? prevToFocus : nextToFocus return handleArrowNav(siblingToFocus) case 'Enter': case 'Space': event.preventDefault() return onChange(isResetBtn ? 0 : childIndex + 1) } event.preventDefault() event.stopPropagation() } /* Group props */ const groupClassNames = getGroupClassNames({ className: userClassNames, radius, readOnly, isDisabled, isDynamic, transition, orientation, absoluteBoxBorderWidth, absoluteStrokeWidth, spaceBetween, spaceInside, }) function getAriaGroupProps() { if (!readOnly) { const isAriaRequired = isRequired && !isDisabled const ariaProps: HTMLProps = { role: 'radiogroup', 'aria-required': isAriaRequired, } if (isAriaRequired) { ariaProps['aria-invalid'] = ratingValue <= 0 } if (typeof visibleLabelId === 'string' && visibleLabelId.length > 0) { ariaProps['aria-labelledby'] = visibleLabelId } else { ariaProps['aria-label'] = invisibleLabel } return ariaProps } return { role: 'img', 'aria-label': invisibleLabel, } } function pushGroupRefs(element: HTMLDivElement) { if (isDynamic && !isRequired) { ;(wrapperRef as MutableRef).current = element } if (externalRef) { ;(externalRef as MutableRef).current = element } } /* Radio props */ function getRefs(childIndex: number) { return { ref: (childNode: HTMLDivElement) => (radioRefs.current[childIndex] = childNode), } } function getKeyboardProps(childIndex: number): HTMLProps { return { tabIndex: tabIndex[childIndex], onKeyDown: (event) => handleKeyDown(event, childIndex), } } function getMouseProps(starIndex: number): HTMLProps { return { onClick: (event) => handleStarClick(event, starIndex), onMouseEnter: () => handleMouseEnter(starIndex), onMouseLeave: handleMouseLeave, } } function getAriaRadioProps(starIndex: number): HTMLProps { if (readOnly) { return {} } const labelProps: HTMLProps = {} if (Array.isArray(visibleItemLabelIds)) { labelProps['aria-labelledby'] = visibleItemLabelIds[starIndex] } else { const radioLabels = Array.isArray(invisibleItemLabels) ? invisibleItemLabels : ratingValues.map((_, index: number) => `Rate ${index + 1}`) labelProps['aria-label'] = radioLabels[starIndex] } if (isDisabled) { labelProps['aria-disabled'] = 'true' } return { role: 'radio', 'aria-checked': starIndex + 1 === ratingValue, ...labelProps, } } function getInteractiveRadioProps(starIndex: number): HTMLProps { if (!isDynamic) { return {} } return { ...getRefs(starIndex), ...getKeyboardProps(starIndex), ...getMouseProps(starIndex), onFocus: (event) => handleFocus(event, starIndex), onBlur: (event) => handleBlur(event), } } function getResetProps(childIndex: number): HTMLProps { return { className: RatingClasses.RESET, role: 'radio', 'aria-label': resetLabel, 'aria-checked': ratingValue === 0, onClick: () => onChange(0), onFocus: (event) => { handleFocus(event, childIndex) wrapperRef.current?.classList.add(RatingClasses.GROUP_RESET) }, onBlur: (event) => { handleBlur(event) wrapperRef.current?.classList.remove(RatingClasses.GROUP_RESET) }, ...getResetTestId(), ...getKeyboardProps(childIndex), ...getRefs(childIndex), ...(isDisabled ? { 'aria-disabled': 'true' } : {}), } } /* SVG props */ function getRatingItemProps(starIndex: number): RatingItemProps { const sharedProps = { itemShapes: Array.isArray(itemShapes) ? itemShapes[starIndex] : itemShapes, itemStrokeWidth: absoluteStrokeWidth, orientation, hasHF: false, testId: getSvgTestIds(starIndex), } if (deservesHF && absoluteHFMode === HFProps.SVG) { sharedProps.hasHF = starIndex === activeStarIndex } return sharedProps } /* Render */ return ( <div id={id} className={groupClassNames} style={{ ...style, ...styles.staticCssVars }} ref={pushGroupRefs} {...getAriaGroupProps()} {...devTestId} > {ratingValues.map((value, index) => ( <Fragment key={value}> <div className={`${RatingClasses.BOX} ${styles.dynamicClassNames[index]}`} style={styles.dynamicCssVars[index]} {...getAriaRadioProps(index)} {...getInteractiveRadioProps(index)} {...getRadioTestIds(index)} > <RatingItem {...getRatingItemProps(index)} /> </div> {shouldRenderReset && index === ratingValues.length - 1 && ( <div {...getResetProps(index + 1)} /> )} </Fragment> ))} </div> ) } ) Rating.displayName = 'Rating'
src/Rating.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/getTabIndex.ts", "retrieved_chunk": "import { TabIndex } from './internalTypes'\nexport function getTabIndex(items: number, selectedIndex: number, hasReset = false): TabIndex[] {\n return Array.from({ length: items }, (_, index) => {\n if (hasReset && selectedIndex < 0) {\n if (index === items - 1) {\n return 0\n }\n return -1\n }\n if (selectedIndex <= 0) {", "score": 0.816985547542572 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " }\n function getTransform() {\n if (svgData) {\n const translateProp = `translate(${svgData?.translateData})`\n if (translateProp === 'translate(0 0)') {\n return {}\n }\n return { transform: translateProp }\n }\n return { transform: undefined }", "score": 0.7807016372680664 }, { "filename": "src/getErrors.ts", "retrieved_chunk": " const errorsObj: ErrorObj = { shouldRender: true, reason: '' }\n if (typeof items !== 'number' || items < 1 || items > 10) {\n return setErrors(errorsObj, 'items is invalid')\n }\n if (!itemShapes) {\n return setErrors(errorsObj, 'itemStyles needs at least the property itemShapes set')\n }\n if (!Array.isArray(itemShapes) && !isValidElement(itemShapes as object | null | undefined)) {\n return setErrors(errorsObj, invalidJSXMsg)\n }", "score": 0.7789560556411743 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " fill: `url('#${uniqId.current}')`,\n }\n }\n return {}\n }\n function getGradientTransformAttr() {\n if (orientation === OrientationProps.VERTICAL) {\n return {\n gradientTransform: 'rotate(90)',\n }", "score": 0.7601749897003174 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " }\n return {}\n }\n function getStrokeAttribute() {\n if (itemStrokeWidth > 0) {\n return {\n strokeWidth: itemStrokeWidth,\n }\n }\n return {}", "score": 0.7598849534988403 } ]
typescript
shouldRender, reason } = getErrors({
import { request } from "../util/request.util"; import { AppConf } from "../app-conf"; import { Chapter } from "./settings.dao"; //See https://www.meetup.com/api/schema/#p03-objects-section for Meetup API details. /** * Represents all the data that is returned from the Meetup API for an event. */ export type MeetupEvent = { id: string; eventUrl: string; title: string; going: number; imageUrl: string; venue: { name: string; address: string; city: string; state: string; } | null; dateTime: string; group: { id: string; name: string; city: string; state: string; urlname: string; }; description: string; }; /** * The raw response from the Meetup API events query. */ type QueryResponse = { data: Record< string, { upcomingEvents: { edges: Array<{ node: MeetupEvent; }>; }; } | null >; }; /** * Get the events from the Meetup API. */ export async function getMeetupEvents( chapters
: Chapter[] ): Promise<Array<MeetupEvent>> {
const finalQuery = formQuery(chapters); const response = await request({ name: "Meetup Event", url: `${AppConf.meetupApiBaseUrl}/gql`, method: "POST", headers: { "Content-Type": "application/json" }, body: { query: finalQuery }, }); return processResponse((await response.json()) as QueryResponse); } const eventFragment = "fragment eventFragment on Event { id eventUrl title description going imageUrl venue { name address city state } dateTime group { id name city state urlname}}"; const groupFragment = "fragment groupFragment on Group { upcomingEvents(input:{first:10}) { edges { node { ...eventFragment } } } }"; /** * Form the query to get the events from the Meetup API. * * @param chapters The chapters to get events for. */ function formQuery(chapters: Array<Chapter>): string { let newQuery = "query {"; for (const i in chapters) { newQuery += `result${i}:groupByUrlname(urlname:"${chapters[i].meetupGroupUrlName}") { ...groupFragment }`; } newQuery += "}" + eventFragment + groupFragment; return newQuery; } /** * Process the response from the query and return a list of events. * * @param response The response from the query. */ function processResponse(response: QueryResponse): Array<MeetupEvent> { const result = [] as Array<MeetupEvent>; for (const group of Object.values(response.data)) { if (group) { for (const event of group.upcomingEvents.edges) { result.push(event.node); } } } return result; }
src/api/dao/meetup.dao.ts
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/service/events.service.ts", "retrieved_chunk": "import { getMeetupEvents, MeetupEvent } from \"../dao/meetup.dao\";\nimport { getChapters } from \"../dao/settings.dao\";\n/**\n * Get a list of all upcoming events for Code and Coffee.\n */\nexport async function getEvents(): Promise<Array<MeetupEvent>> {\n const chapters = await getChapters();\n const events = await getMeetupEvents(chapters);\n return events.sort((a, b) => {\n return new Date(a.dateTime).getTime() - new Date(b.dateTime).getTime();", "score": 0.8403693437576294 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": " name: string;\n github: string;\n email: Array<string>;\n emailTitlePrepend: string;\n};\n/**\n * Get a list of all the Code and Coffee Chapters.\n */\nexport async function getChapters(): Promise<Chapter[]> {\n return (await (", "score": 0.8243453502655029 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": "}\n/**\n * Get all the notification settings.\n */\nexport async function getNotificationSettings(): Promise<\n Array<NotificationSetting>\n> {\n return await (\n await request({\n name: \"Notification Settings\",", "score": 0.7978509068489075 }, { "filename": "src/ui/calendar/coffee.dao.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nimport { WebConf } from \"../web-conf\";\n/**\n * Get the details of all events from the Code and Coffee service.\n */\nexport async function getEvents(): Promise<EventsResponse> {\n const response = await fetch(`${WebConf.rootHost}/info/events`, {\n method: \"GET\",\n });\n return response.json();", "score": 0.7820388078689575 }, { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nexport type EventStats = {\n totalEvents: number;\n totalActiveChapters: number;\n totalRSVPs: number;\n};\n/**\n * Gets the stats for all the current events.\n *\n * @param events The events to get stats from", "score": 0.773054838180542 } ]
typescript
: Chapter[] ): Promise<Array<MeetupEvent>> {
import { useRef, useState } from 'react' import { areNum, getNewPosition, getDefsTestId, getUniqueId, toSecondDecimal, useIsomorphicLayoutEffect, } from './utils' import { RatingClasses, OrientationProps } from './constants' import { RatingItemProps, SvgData } from './internalTypes' export function RatingItem({ itemShapes, testId, itemStrokeWidth = 0, orientation = OrientationProps.HORIZONTAL, hasHF = false, }: RatingItemProps) { const strokeOffset = itemStrokeWidth > 0 ? -(itemStrokeWidth / 2) : 0 const translateOffset = itemStrokeWidth > 0 ? `${strokeOffset} ${strokeOffset}` : '0 0' const svgRef = useRef<SVGPathElement | null>(null) const uniqId = useRef<string | null>(null) const [svgData, setSvgData] = useState<SvgData | null>(null) useIsomorphicLayoutEffect(() => { if (hasHF && !uniqId.current) { uniqId.current = `rr_hf_${getUniqueId()}` } if (svgRef.current) { const { width: svgWidth, height: svgHeight, x: svgXPos, y: svgYPos, } = svgRef.current.getBBox() if (areNum(svgWidth, svgHeight, svgXPos, svgYPos)) { const viewBox = `${translateOffset} ${toSecondDecimal( svgWidth + itemStrokeWidth )} ${toSecondDecimal(svgHeight + itemStrokeWidth)}` const translateData = `${getNewPosition(svgXPos)} ${getNewPosition(svgYPos)}` setSvgData({ viewBox, translateData, }) } } }, [itemShapes, itemStrokeWidth, hasHF]) /* Props */ function getHFAttr() { if (hasHF) { return { fill: `url('#${uniqId.current}')`, } } return {} } function getGradientTransformAttr() { if (orientation === OrientationProps.VERTICAL) { return { gradientTransform: 'rotate(90)', } } return {} } function getStrokeAttribute() { if (itemStrokeWidth > 0) { return { strokeWidth: itemStrokeWidth, } } return {} } function getTransform() { if (svgData) { const translateProp = `translate(${svgData?.translateData})` if (translateProp === 'translate(0 0)') { return {} } return { transform: translateProp } } return { transform: undefined } } return ( <svg aria-hidden="true"
className={RatingClasses.SVG}
xmlns="http://www.w3.org/2000/svg" viewBox={svgData ? svgData.viewBox : '0 0 0 0'} preserveAspectRatio="xMidYMid meet" {...getStrokeAttribute()} {...testId} > {hasHF && uniqId.current && ( <defs {...getDefsTestId()}> <linearGradient id={uniqId.current} {...getGradientTransformAttr()}> <stop className={RatingClasses.DEF_50} offset="50%" /> <stop className={RatingClasses.DEF_100} offset="50%" /> </linearGradient> </defs> )} <g ref={svgRef} shapeRendering="geometricPrecision" {...getTransform()} {...getHFAttr()}> {itemShapes} </g> </svg> ) }
src/RatingItem.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/getStaticClassNames.ts", "retrieved_chunk": " case TransitionProps.COLORS:\n return TransitionClasses.COLORS\n default:\n return ''\n }\n}\n/* c8 ignore stop */\n/* c8 ignore start */\nexport function getRadiusClassName(radiusProp: unknown): MaybeEmptyClassName {\n switch (radiusProp) {", "score": 0.7805430293083191 }, { "filename": "src/Rating.tsx", "retrieved_chunk": " event.preventDefault()\n return onChange(isResetBtn ? 0 : childIndex + 1)\n }\n event.preventDefault()\n event.stopPropagation()\n }\n /* Group props */\n const groupClassNames = getGroupClassNames({\n className: userClassNames,\n radius,", "score": 0.7766262292861938 }, { "filename": "src/Rating.tsx", "retrieved_chunk": " onBlur: (event) => handleBlur(event),\n }\n }\n function getResetProps(childIndex: number): HTMLProps {\n return {\n className: RatingClasses.RESET,\n role: 'radio',\n 'aria-label': resetLabel,\n 'aria-checked': ratingValue === 0,\n onClick: () => onChange(0),", "score": 0.7743777632713318 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": " /** Custom shapes and colors, visit https://github.com/smastrom/react-rating for more info. */\n itemStyles?: ItemStyles\n id?: string\n className?: string\n style?: CSSProperties\n}\nexport type ReadOnlyProps = {\n /** Whether to half-fill the SVG or the box. */\n halfFillMode?: HF\n}", "score": 0.770016074180603 }, { "filename": "src/Rating.tsx", "retrieved_chunk": " ...getRefs(childIndex),\n ...(isDisabled ? { 'aria-disabled': 'true' } : {}),\n }\n }\n /* SVG props */\n function getRatingItemProps(starIndex: number): RatingItemProps {\n const sharedProps = {\n itemShapes: Array.isArray(itemShapes) ? itemShapes[starIndex] : itemShapes,\n itemStrokeWidth: absoluteStrokeWidth,\n orientation,", "score": 0.7657914161682129 } ]
typescript
className={RatingClasses.SVG}
import { forwardRef, useMemo, useCallback, useRef, useState, useEffect, Fragment, KeyboardEvent, } from 'react' import { RatingItem } from './RatingItem' import { getDynamicCssVars } from './getDynamicCssVars' import { getGroupClassNames } from './getGroupClassNames' import { getActiveClassNames } from './getActiveClassNames' import { getHFClassNames } from './getHFClassNames' import { getStaticCssVars } from './getStaticCssVars' import { getColors } from './getColors' import { getTabIndex } from './getTabIndex' import { getErrors } from './getErrors' import { getIntersectionIndex, getNumber, getRadioTestIds, getSvgTestIds, devTestId, getResetTestId, isGraphicalValueInteger, isRTLDir, useIsomorphicLayoutEffect, noop, } from './utils' import { Sizes, OrientationProps, TransitionProps, HFProps, RatingClasses } from './constants' import { defaultItemStyles } from './defaultItemStyles' import { RatingProps, Rating as RatingComponent } from './exportedTypes' import { StylesState, RequireAtLeastOne, ValidArrayColors, TabIndex, RatingItemProps, MouseEvent, FocusEvent, HTMLProps, MutableRef, } from './internalTypes' /** Thank you for using **React Rating**. * Visit https://github.com/smastrom/react-rating to read the full documentation. */ export const Rating:
typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>( ( {
value, items = 5, readOnly = false, onChange = noop, onHoverChange = noop, onFocus = noop, onBlur = noop, isDisabled = false, highlightOnlySelected = false, orientation = OrientationProps.HORIZONTAL, spaceBetween = Sizes.NONE, spaceInside = Sizes.SMALL, radius = Sizes.NONE, transition = TransitionProps.COLORS, itemStyles = defaultItemStyles, isRequired = false, halfFillMode = HFProps.SVG, visibleLabelId, visibleItemLabelIds, invisibleItemLabels, invisibleLabel = readOnly ? value > 0 ? `Rated ${value} on ${items}` : 'Not rated' : 'Rating Selection', resetLabel = 'Reset rating', id, className, style, }, externalRef ) => { /* Helpers */ const ratingValues = Array.from({ length: items }, (_, index) => index + 1) const hasPrecision = readOnly && !Number.isInteger(value) const isEligibleForHF = hasPrecision && !highlightOnlySelected const isNotEligibleForHF = hasPrecision && highlightOnlySelected const ratingValue = isNotEligibleForHF ? Math.round(value) : value const isDynamic = !readOnly && !isDisabled const needsDynamicCssVars = ratingValue >= 0.25 const userClassNames = typeof className === 'string' ? className : '' const absoluteHFMode = halfFillMode === HFProps.BOX ? HFProps.BOX : HFProps.SVG const deservesHF = isEligibleForHF && !isGraphicalValueInteger(ratingValue) const shouldRenderReset = !isRequired && !readOnly const tabIndexItems = isRequired ? items : items + 1 const activeStarIndex = isEligibleForHF ? getIntersectionIndex(ratingValues, ratingValue) : ratingValues.indexOf(ratingValue) /* Deps/Callbacks */ const { staticColors, arrayColors, itemShapes, absoluteStrokeWidth, absoluteBoxBorderWidth } = useMemo(() => { const { itemShapes, itemStrokeWidth, boxBorderWidth, ...colors } = itemStyles const userColors = getColors(colors) return { itemShapes, absoluteStrokeWidth: getNumber(itemStrokeWidth), absoluteBoxBorderWidth: getNumber(boxBorderWidth), ...userColors, } }, [itemStyles]) const hasArrayColors = Object.keys(arrayColors).length > 0 const getDynamicStyles = useCallback( (starIndex: number, shouldGetCssVars: boolean) => ({ dynamicClassNames: deservesHF ? getHFClassNames(ratingValue, items, absoluteHFMode) : getActiveClassNames(highlightOnlySelected, items, starIndex), dynamicCssVars: shouldGetCssVars && hasArrayColors ? getDynamicCssVars( arrayColors as RequireAtLeastOne<ValidArrayColors>, starIndex, highlightOnlySelected ) : [], }), [ arrayColors, hasArrayColors, highlightOnlySelected, absoluteHFMode, deservesHF, items, ratingValue, ] ) const saveTabIndex = useCallback( () => setTabIndex(getTabIndex(tabIndexItems, activeStarIndex, !isRequired)), [activeStarIndex, tabIndexItems, isRequired] ) /* Refs */ const skipStylesMount = useRef(true) const skipTabMount = useRef(true) const wrapperRef = useRef<HTMLDivElement>(null) const radioRefs = useRef<HTMLDivElement[]>([]) const isRTL = useRef(false) /* State */ const [styles, setStyles] = useState<StylesState>({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) const [tabIndex, setTabIndex] = useState<TabIndex[]>(() => { if (isDynamic) { return getTabIndex(tabIndexItems, activeStarIndex, !isRequired) } return [] }) /* Effects */ useIsomorphicLayoutEffect(() => { if (isDynamic && radioRefs.current) { isRTL.current = isRTLDir(radioRefs.current[0]) } }, [isDynamic]) useEffect(() => { if (!skipStylesMount.current) { return setStyles({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } skipStylesMount.current = false }, [ staticColors, getDynamicStyles, absoluteBoxBorderWidth, activeStarIndex, needsDynamicCssVars, ]) useEffect(() => { if (!skipTabMount.current && isDynamic) { return saveTabIndex() } skipTabMount.current = false }, [isDynamic, saveTabIndex]) /* Log critical errors, return null */ const { shouldRender, reason } = getErrors({ items, itemShapes, }) if (!shouldRender) { console.error(reason) return null } /* Event Handlers */ function handleWhenNeeded( event: FocusEvent | MouseEvent, fromOutsideCallback: () => void, // eslint-disable-next-line @typescript-eslint/no-empty-function fromInsideCallback: () => void = () => {} ) { const fromInside = radioRefs.current.some((radio) => radio === event.relatedTarget) if (!fromInside) { fromOutsideCallback() } else { fromInsideCallback() } } function handleStarLeave() { onHoverChange(0) saveTabIndex() } function handleStarClick(event: MouseEvent, clickedIndex: number) { event.stopPropagation() if (!isRequired && activeStarIndex === clickedIndex) { onChange(0) } else { onChange(clickedIndex + 1) } } function handleMouseEnter(starIndex: number) { onHoverChange(starIndex + 1) setStyles({ ...styles, ...getDynamicStyles(starIndex, true) }) } function handleMouseLeave(event: MouseEvent) { handleWhenNeeded(event, () => { handleStarLeave() }) setStyles({ ...styles, ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } function handleBlur(event: FocusEvent) { handleWhenNeeded(event, () => { handleStarLeave() onBlur() }) } function handleFocus(event: FocusEvent, childIndex: number) { const isResetBtn = !isRequired && childIndex === ratingValues.length const hoveredValue = isResetBtn ? 0 : childIndex + 1 handleWhenNeeded( event, () => { onFocus() onHoverChange(hoveredValue) }, () => { onHoverChange(hoveredValue) } ) } /* Keyboard */ function handleArrowNav(siblingToFocus: number) { setTabIndex(getTabIndex(tabIndexItems, siblingToFocus, !isRequired)) radioRefs.current[siblingToFocus].focus() } function handleKeyDown(event: KeyboardEvent<HTMLDivElement>, childIndex: number) { let siblingToFocus = 0 const lastSibling = isRequired ? ratingValues.length - 1 : ratingValues.length const prevSibling = childIndex - 1 const nextSibling = childIndex + 1 const isResetBtn = !isRequired && childIndex === ratingValues.length const isFiringFromLast = lastSibling === childIndex const isFiringFromFirst = childIndex === 0 const prevToFocus = isFiringFromFirst ? lastSibling : prevSibling const nextToFocus = isFiringFromLast ? 0 : nextSibling switch (event.code) { case 'Shift': case 'Tab': return true case 'ArrowDown': case 'ArrowRight': siblingToFocus = !isRTL.current ? nextToFocus : prevToFocus return handleArrowNav(siblingToFocus) case 'ArrowUp': case 'ArrowLeft': siblingToFocus = !isRTL.current ? prevToFocus : nextToFocus return handleArrowNav(siblingToFocus) case 'Enter': case 'Space': event.preventDefault() return onChange(isResetBtn ? 0 : childIndex + 1) } event.preventDefault() event.stopPropagation() } /* Group props */ const groupClassNames = getGroupClassNames({ className: userClassNames, radius, readOnly, isDisabled, isDynamic, transition, orientation, absoluteBoxBorderWidth, absoluteStrokeWidth, spaceBetween, spaceInside, }) function getAriaGroupProps() { if (!readOnly) { const isAriaRequired = isRequired && !isDisabled const ariaProps: HTMLProps = { role: 'radiogroup', 'aria-required': isAriaRequired, } if (isAriaRequired) { ariaProps['aria-invalid'] = ratingValue <= 0 } if (typeof visibleLabelId === 'string' && visibleLabelId.length > 0) { ariaProps['aria-labelledby'] = visibleLabelId } else { ariaProps['aria-label'] = invisibleLabel } return ariaProps } return { role: 'img', 'aria-label': invisibleLabel, } } function pushGroupRefs(element: HTMLDivElement) { if (isDynamic && !isRequired) { ;(wrapperRef as MutableRef).current = element } if (externalRef) { ;(externalRef as MutableRef).current = element } } /* Radio props */ function getRefs(childIndex: number) { return { ref: (childNode: HTMLDivElement) => (radioRefs.current[childIndex] = childNode), } } function getKeyboardProps(childIndex: number): HTMLProps { return { tabIndex: tabIndex[childIndex], onKeyDown: (event) => handleKeyDown(event, childIndex), } } function getMouseProps(starIndex: number): HTMLProps { return { onClick: (event) => handleStarClick(event, starIndex), onMouseEnter: () => handleMouseEnter(starIndex), onMouseLeave: handleMouseLeave, } } function getAriaRadioProps(starIndex: number): HTMLProps { if (readOnly) { return {} } const labelProps: HTMLProps = {} if (Array.isArray(visibleItemLabelIds)) { labelProps['aria-labelledby'] = visibleItemLabelIds[starIndex] } else { const radioLabels = Array.isArray(invisibleItemLabels) ? invisibleItemLabels : ratingValues.map((_, index: number) => `Rate ${index + 1}`) labelProps['aria-label'] = radioLabels[starIndex] } if (isDisabled) { labelProps['aria-disabled'] = 'true' } return { role: 'radio', 'aria-checked': starIndex + 1 === ratingValue, ...labelProps, } } function getInteractiveRadioProps(starIndex: number): HTMLProps { if (!isDynamic) { return {} } return { ...getRefs(starIndex), ...getKeyboardProps(starIndex), ...getMouseProps(starIndex), onFocus: (event) => handleFocus(event, starIndex), onBlur: (event) => handleBlur(event), } } function getResetProps(childIndex: number): HTMLProps { return { className: RatingClasses.RESET, role: 'radio', 'aria-label': resetLabel, 'aria-checked': ratingValue === 0, onClick: () => onChange(0), onFocus: (event) => { handleFocus(event, childIndex) wrapperRef.current?.classList.add(RatingClasses.GROUP_RESET) }, onBlur: (event) => { handleBlur(event) wrapperRef.current?.classList.remove(RatingClasses.GROUP_RESET) }, ...getResetTestId(), ...getKeyboardProps(childIndex), ...getRefs(childIndex), ...(isDisabled ? { 'aria-disabled': 'true' } : {}), } } /* SVG props */ function getRatingItemProps(starIndex: number): RatingItemProps { const sharedProps = { itemShapes: Array.isArray(itemShapes) ? itemShapes[starIndex] : itemShapes, itemStrokeWidth: absoluteStrokeWidth, orientation, hasHF: false, testId: getSvgTestIds(starIndex), } if (deservesHF && absoluteHFMode === HFProps.SVG) { sharedProps.hasHF = starIndex === activeStarIndex } return sharedProps } /* Render */ return ( <div id={id} className={groupClassNames} style={{ ...style, ...styles.staticCssVars }} ref={pushGroupRefs} {...getAriaGroupProps()} {...devTestId} > {ratingValues.map((value, index) => ( <Fragment key={value}> <div className={`${RatingClasses.BOX} ${styles.dynamicClassNames[index]}`} style={styles.dynamicCssVars[index]} {...getAriaRadioProps(index)} {...getInteractiveRadioProps(index)} {...getRadioTestIds(index)} > <RatingItem {...getRatingItemProps(index)} /> </div> {shouldRenderReset && index === ratingValues.length - 1 && ( <div {...getResetProps(index + 1)} /> )} </Fragment> ))} </div> ) } ) Rating.displayName = 'Rating'
src/Rating.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/exportedTypes.ts", "retrieved_chunk": " /** Custom shapes and colors, visit https://github.com/smastrom/react-rating for more info. */\n itemStyles?: ItemStyles\n id?: string\n className?: string\n style?: CSSProperties\n}\nexport type ReadOnlyProps = {\n /** Whether to half-fill the SVG or the box. */\n halfFillMode?: HF\n}", "score": 0.8187940716743469 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": "import { useRef, useState } from 'react'\nimport {\n areNum,\n getNewPosition,\n getDefsTestId,\n getUniqueId,\n toSecondDecimal,\n useIsomorphicLayoutEffect,\n} from './utils'\nimport { RatingClasses, OrientationProps } from './constants'", "score": 0.7920961976051331 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": " /** Accessible label for the invisible reset radio. Effective if `isRequired` is set to **false**. */\n resetLabel?: string\n}\nexport type RatingProps = SharedProps & ReadOnlyProps & InputProps\nexport declare const Rating: ForwardRefExoticComponent<RatingProps & RefAttributes<HTMLDivElement>>\nexport declare const Star: JSX.Element\nexport declare const ThinStar: JSX.Element\nexport declare const RoundedStar: JSX.Element\nexport declare const ThinRoundedStar: JSX.Element\nexport declare const StickerStar: JSX.Element", "score": 0.7894612550735474 }, { "filename": "src/internalTypes.ts", "retrieved_chunk": "export type SvgData = {\n viewBox: string\n translateData: string\n}\nexport type NonNullProp<K extends keyof RatingProps> = NonNullable<RatingProps[`${K}`]>\nexport type HTMLProps = React.HTMLProps<HTMLDivElement>\nexport type MouseEvent = React.MouseEvent<HTMLDivElement>\nexport type FocusEvent = React.FocusEvent<HTMLDivElement>\nexport type MutableRef = React.MutableRefObject<HTMLDivElement | null>", "score": 0.7878155708312988 }, { "filename": "src/getErrors.ts", "retrieved_chunk": "import { isValidElement } from 'react'\nimport { ItemStyles, RatingProps } from './exportedTypes'\nimport Package from '../package.json'\ntype ErrorObj = {\n shouldRender: boolean\n reason: string\n}\nconst getErrorReason = (reason: string) =>\n `[${Package.name}] - Nothing's returned from rendering. Reason: ${reason}.`\nfunction setErrors(targetObj: ErrorObj, reason: string) {", "score": 0.782195508480072 } ]
typescript
typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>( ( {
import { forwardRef, useMemo, useCallback, useRef, useState, useEffect, Fragment, KeyboardEvent, } from 'react' import { RatingItem } from './RatingItem' import { getDynamicCssVars } from './getDynamicCssVars' import { getGroupClassNames } from './getGroupClassNames' import { getActiveClassNames } from './getActiveClassNames' import { getHFClassNames } from './getHFClassNames' import { getStaticCssVars } from './getStaticCssVars' import { getColors } from './getColors' import { getTabIndex } from './getTabIndex' import { getErrors } from './getErrors' import { getIntersectionIndex, getNumber, getRadioTestIds, getSvgTestIds, devTestId, getResetTestId, isGraphicalValueInteger, isRTLDir, useIsomorphicLayoutEffect, noop, } from './utils' import { Sizes, OrientationProps, TransitionProps, HFProps, RatingClasses } from './constants' import { defaultItemStyles } from './defaultItemStyles' import { RatingProps, Rating as RatingComponent } from './exportedTypes' import { StylesState, RequireAtLeastOne, ValidArrayColors, TabIndex, RatingItemProps, MouseEvent, FocusEvent, HTMLProps, MutableRef, } from './internalTypes' /** Thank you for using **React Rating**. * Visit https://github.com/smastrom/react-rating to read the full documentation. */
export const Rating: typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>( ( {
value, items = 5, readOnly = false, onChange = noop, onHoverChange = noop, onFocus = noop, onBlur = noop, isDisabled = false, highlightOnlySelected = false, orientation = OrientationProps.HORIZONTAL, spaceBetween = Sizes.NONE, spaceInside = Sizes.SMALL, radius = Sizes.NONE, transition = TransitionProps.COLORS, itemStyles = defaultItemStyles, isRequired = false, halfFillMode = HFProps.SVG, visibleLabelId, visibleItemLabelIds, invisibleItemLabels, invisibleLabel = readOnly ? value > 0 ? `Rated ${value} on ${items}` : 'Not rated' : 'Rating Selection', resetLabel = 'Reset rating', id, className, style, }, externalRef ) => { /* Helpers */ const ratingValues = Array.from({ length: items }, (_, index) => index + 1) const hasPrecision = readOnly && !Number.isInteger(value) const isEligibleForHF = hasPrecision && !highlightOnlySelected const isNotEligibleForHF = hasPrecision && highlightOnlySelected const ratingValue = isNotEligibleForHF ? Math.round(value) : value const isDynamic = !readOnly && !isDisabled const needsDynamicCssVars = ratingValue >= 0.25 const userClassNames = typeof className === 'string' ? className : '' const absoluteHFMode = halfFillMode === HFProps.BOX ? HFProps.BOX : HFProps.SVG const deservesHF = isEligibleForHF && !isGraphicalValueInteger(ratingValue) const shouldRenderReset = !isRequired && !readOnly const tabIndexItems = isRequired ? items : items + 1 const activeStarIndex = isEligibleForHF ? getIntersectionIndex(ratingValues, ratingValue) : ratingValues.indexOf(ratingValue) /* Deps/Callbacks */ const { staticColors, arrayColors, itemShapes, absoluteStrokeWidth, absoluteBoxBorderWidth } = useMemo(() => { const { itemShapes, itemStrokeWidth, boxBorderWidth, ...colors } = itemStyles const userColors = getColors(colors) return { itemShapes, absoluteStrokeWidth: getNumber(itemStrokeWidth), absoluteBoxBorderWidth: getNumber(boxBorderWidth), ...userColors, } }, [itemStyles]) const hasArrayColors = Object.keys(arrayColors).length > 0 const getDynamicStyles = useCallback( (starIndex: number, shouldGetCssVars: boolean) => ({ dynamicClassNames: deservesHF ? getHFClassNames(ratingValue, items, absoluteHFMode) : getActiveClassNames(highlightOnlySelected, items, starIndex), dynamicCssVars: shouldGetCssVars && hasArrayColors ? getDynamicCssVars( arrayColors as RequireAtLeastOne<ValidArrayColors>, starIndex, highlightOnlySelected ) : [], }), [ arrayColors, hasArrayColors, highlightOnlySelected, absoluteHFMode, deservesHF, items, ratingValue, ] ) const saveTabIndex = useCallback( () => setTabIndex(getTabIndex(tabIndexItems, activeStarIndex, !isRequired)), [activeStarIndex, tabIndexItems, isRequired] ) /* Refs */ const skipStylesMount = useRef(true) const skipTabMount = useRef(true) const wrapperRef = useRef<HTMLDivElement>(null) const radioRefs = useRef<HTMLDivElement[]>([]) const isRTL = useRef(false) /* State */ const [styles, setStyles] = useState<StylesState>({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) const [tabIndex, setTabIndex] = useState<TabIndex[]>(() => { if (isDynamic) { return getTabIndex(tabIndexItems, activeStarIndex, !isRequired) } return [] }) /* Effects */ useIsomorphicLayoutEffect(() => { if (isDynamic && radioRefs.current) { isRTL.current = isRTLDir(radioRefs.current[0]) } }, [isDynamic]) useEffect(() => { if (!skipStylesMount.current) { return setStyles({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } skipStylesMount.current = false }, [ staticColors, getDynamicStyles, absoluteBoxBorderWidth, activeStarIndex, needsDynamicCssVars, ]) useEffect(() => { if (!skipTabMount.current && isDynamic) { return saveTabIndex() } skipTabMount.current = false }, [isDynamic, saveTabIndex]) /* Log critical errors, return null */ const { shouldRender, reason } = getErrors({ items, itemShapes, }) if (!shouldRender) { console.error(reason) return null } /* Event Handlers */ function handleWhenNeeded( event: FocusEvent | MouseEvent, fromOutsideCallback: () => void, // eslint-disable-next-line @typescript-eslint/no-empty-function fromInsideCallback: () => void = () => {} ) { const fromInside = radioRefs.current.some((radio) => radio === event.relatedTarget) if (!fromInside) { fromOutsideCallback() } else { fromInsideCallback() } } function handleStarLeave() { onHoverChange(0) saveTabIndex() } function handleStarClick(event: MouseEvent, clickedIndex: number) { event.stopPropagation() if (!isRequired && activeStarIndex === clickedIndex) { onChange(0) } else { onChange(clickedIndex + 1) } } function handleMouseEnter(starIndex: number) { onHoverChange(starIndex + 1) setStyles({ ...styles, ...getDynamicStyles(starIndex, true) }) } function handleMouseLeave(event: MouseEvent) { handleWhenNeeded(event, () => { handleStarLeave() }) setStyles({ ...styles, ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } function handleBlur(event: FocusEvent) { handleWhenNeeded(event, () => { handleStarLeave() onBlur() }) } function handleFocus(event: FocusEvent, childIndex: number) { const isResetBtn = !isRequired && childIndex === ratingValues.length const hoveredValue = isResetBtn ? 0 : childIndex + 1 handleWhenNeeded( event, () => { onFocus() onHoverChange(hoveredValue) }, () => { onHoverChange(hoveredValue) } ) } /* Keyboard */ function handleArrowNav(siblingToFocus: number) { setTabIndex(getTabIndex(tabIndexItems, siblingToFocus, !isRequired)) radioRefs.current[siblingToFocus].focus() } function handleKeyDown(event: KeyboardEvent<HTMLDivElement>, childIndex: number) { let siblingToFocus = 0 const lastSibling = isRequired ? ratingValues.length - 1 : ratingValues.length const prevSibling = childIndex - 1 const nextSibling = childIndex + 1 const isResetBtn = !isRequired && childIndex === ratingValues.length const isFiringFromLast = lastSibling === childIndex const isFiringFromFirst = childIndex === 0 const prevToFocus = isFiringFromFirst ? lastSibling : prevSibling const nextToFocus = isFiringFromLast ? 0 : nextSibling switch (event.code) { case 'Shift': case 'Tab': return true case 'ArrowDown': case 'ArrowRight': siblingToFocus = !isRTL.current ? nextToFocus : prevToFocus return handleArrowNav(siblingToFocus) case 'ArrowUp': case 'ArrowLeft': siblingToFocus = !isRTL.current ? prevToFocus : nextToFocus return handleArrowNav(siblingToFocus) case 'Enter': case 'Space': event.preventDefault() return onChange(isResetBtn ? 0 : childIndex + 1) } event.preventDefault() event.stopPropagation() } /* Group props */ const groupClassNames = getGroupClassNames({ className: userClassNames, radius, readOnly, isDisabled, isDynamic, transition, orientation, absoluteBoxBorderWidth, absoluteStrokeWidth, spaceBetween, spaceInside, }) function getAriaGroupProps() { if (!readOnly) { const isAriaRequired = isRequired && !isDisabled const ariaProps: HTMLProps = { role: 'radiogroup', 'aria-required': isAriaRequired, } if (isAriaRequired) { ariaProps['aria-invalid'] = ratingValue <= 0 } if (typeof visibleLabelId === 'string' && visibleLabelId.length > 0) { ariaProps['aria-labelledby'] = visibleLabelId } else { ariaProps['aria-label'] = invisibleLabel } return ariaProps } return { role: 'img', 'aria-label': invisibleLabel, } } function pushGroupRefs(element: HTMLDivElement) { if (isDynamic && !isRequired) { ;(wrapperRef as MutableRef).current = element } if (externalRef) { ;(externalRef as MutableRef).current = element } } /* Radio props */ function getRefs(childIndex: number) { return { ref: (childNode: HTMLDivElement) => (radioRefs.current[childIndex] = childNode), } } function getKeyboardProps(childIndex: number): HTMLProps { return { tabIndex: tabIndex[childIndex], onKeyDown: (event) => handleKeyDown(event, childIndex), } } function getMouseProps(starIndex: number): HTMLProps { return { onClick: (event) => handleStarClick(event, starIndex), onMouseEnter: () => handleMouseEnter(starIndex), onMouseLeave: handleMouseLeave, } } function getAriaRadioProps(starIndex: number): HTMLProps { if (readOnly) { return {} } const labelProps: HTMLProps = {} if (Array.isArray(visibleItemLabelIds)) { labelProps['aria-labelledby'] = visibleItemLabelIds[starIndex] } else { const radioLabels = Array.isArray(invisibleItemLabels) ? invisibleItemLabels : ratingValues.map((_, index: number) => `Rate ${index + 1}`) labelProps['aria-label'] = radioLabels[starIndex] } if (isDisabled) { labelProps['aria-disabled'] = 'true' } return { role: 'radio', 'aria-checked': starIndex + 1 === ratingValue, ...labelProps, } } function getInteractiveRadioProps(starIndex: number): HTMLProps { if (!isDynamic) { return {} } return { ...getRefs(starIndex), ...getKeyboardProps(starIndex), ...getMouseProps(starIndex), onFocus: (event) => handleFocus(event, starIndex), onBlur: (event) => handleBlur(event), } } function getResetProps(childIndex: number): HTMLProps { return { className: RatingClasses.RESET, role: 'radio', 'aria-label': resetLabel, 'aria-checked': ratingValue === 0, onClick: () => onChange(0), onFocus: (event) => { handleFocus(event, childIndex) wrapperRef.current?.classList.add(RatingClasses.GROUP_RESET) }, onBlur: (event) => { handleBlur(event) wrapperRef.current?.classList.remove(RatingClasses.GROUP_RESET) }, ...getResetTestId(), ...getKeyboardProps(childIndex), ...getRefs(childIndex), ...(isDisabled ? { 'aria-disabled': 'true' } : {}), } } /* SVG props */ function getRatingItemProps(starIndex: number): RatingItemProps { const sharedProps = { itemShapes: Array.isArray(itemShapes) ? itemShapes[starIndex] : itemShapes, itemStrokeWidth: absoluteStrokeWidth, orientation, hasHF: false, testId: getSvgTestIds(starIndex), } if (deservesHF && absoluteHFMode === HFProps.SVG) { sharedProps.hasHF = starIndex === activeStarIndex } return sharedProps } /* Render */ return ( <div id={id} className={groupClassNames} style={{ ...style, ...styles.staticCssVars }} ref={pushGroupRefs} {...getAriaGroupProps()} {...devTestId} > {ratingValues.map((value, index) => ( <Fragment key={value}> <div className={`${RatingClasses.BOX} ${styles.dynamicClassNames[index]}`} style={styles.dynamicCssVars[index]} {...getAriaRadioProps(index)} {...getInteractiveRadioProps(index)} {...getRadioTestIds(index)} > <RatingItem {...getRatingItemProps(index)} /> </div> {shouldRenderReset && index === ratingValues.length - 1 && ( <div {...getResetProps(index + 1)} /> )} </Fragment> ))} </div> ) } ) Rating.displayName = 'Rating'
src/Rating.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/exportedTypes.ts", "retrieved_chunk": " /** Custom shapes and colors, visit https://github.com/smastrom/react-rating for more info. */\n itemStyles?: ItemStyles\n id?: string\n className?: string\n style?: CSSProperties\n}\nexport type ReadOnlyProps = {\n /** Whether to half-fill the SVG or the box. */\n halfFillMode?: HF\n}", "score": 0.8326342701911926 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": "import { useRef, useState } from 'react'\nimport {\n areNum,\n getNewPosition,\n getDefsTestId,\n getUniqueId,\n toSecondDecimal,\n useIsomorphicLayoutEffect,\n} from './utils'\nimport { RatingClasses, OrientationProps } from './constants'", "score": 0.8061985969543457 }, { "filename": "src/internalTypes.ts", "retrieved_chunk": "export type SvgData = {\n viewBox: string\n translateData: string\n}\nexport type NonNullProp<K extends keyof RatingProps> = NonNullable<RatingProps[`${K}`]>\nexport type HTMLProps = React.HTMLProps<HTMLDivElement>\nexport type MouseEvent = React.MouseEvent<HTMLDivElement>\nexport type FocusEvent = React.FocusEvent<HTMLDivElement>\nexport type MutableRef = React.MutableRefObject<HTMLDivElement | null>", "score": 0.8028607368469238 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": " /** Accessible label for the invisible reset radio. Effective if `isRequired` is set to **false**. */\n resetLabel?: string\n}\nexport type RatingProps = SharedProps & ReadOnlyProps & InputProps\nexport declare const Rating: ForwardRefExoticComponent<RatingProps & RefAttributes<HTMLDivElement>>\nexport declare const Star: JSX.Element\nexport declare const ThinStar: JSX.Element\nexport declare const RoundedStar: JSX.Element\nexport declare const ThinRoundedStar: JSX.Element\nexport declare const StickerStar: JSX.Element", "score": 0.7992936372756958 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": "import {\n CSSProperties,\n ForwardRefExoticComponent,\n RefAttributes,\n Dispatch,\n SetStateAction,\n} from 'react'\nexport type MaybeArrayColors = {\n /** Active fill color of the SVG, it can be an array of colors in ascending order. */\n activeFillColor?: string | string[]", "score": 0.7878457307815552 } ]
typescript
export const Rating: typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>( ( {
import { forwardRef, useMemo, useCallback, useRef, useState, useEffect, Fragment, KeyboardEvent, } from 'react' import { RatingItem } from './RatingItem' import { getDynamicCssVars } from './getDynamicCssVars' import { getGroupClassNames } from './getGroupClassNames' import { getActiveClassNames } from './getActiveClassNames' import { getHFClassNames } from './getHFClassNames' import { getStaticCssVars } from './getStaticCssVars' import { getColors } from './getColors' import { getTabIndex } from './getTabIndex' import { getErrors } from './getErrors' import { getIntersectionIndex, getNumber, getRadioTestIds, getSvgTestIds, devTestId, getResetTestId, isGraphicalValueInteger, isRTLDir, useIsomorphicLayoutEffect, noop, } from './utils' import { Sizes, OrientationProps, TransitionProps, HFProps, RatingClasses } from './constants' import { defaultItemStyles } from './defaultItemStyles' import { RatingProps, Rating as RatingComponent } from './exportedTypes' import { StylesState, RequireAtLeastOne, ValidArrayColors, TabIndex, RatingItemProps, MouseEvent, FocusEvent, HTMLProps, MutableRef, } from './internalTypes' /** Thank you for using **React Rating**. * Visit https://github.com/smastrom/react-rating to read the full documentation. */ export const Rating: typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>( ( { value, items = 5, readOnly = false, onChange = noop, onHoverChange = noop, onFocus = noop, onBlur = noop, isDisabled = false, highlightOnlySelected = false, orientation = OrientationProps.HORIZONTAL, spaceBetween = Sizes.NONE, spaceInside = Sizes.SMALL, radius = Sizes.NONE, transition = TransitionProps.COLORS, itemStyles = defaultItemStyles, isRequired = false, halfFillMode = HFProps.SVG, visibleLabelId, visibleItemLabelIds, invisibleItemLabels, invisibleLabel = readOnly ? value > 0 ? `Rated ${value} on ${items}` : 'Not rated' : 'Rating Selection', resetLabel = 'Reset rating', id, className, style, }, externalRef ) => { /* Helpers */ const ratingValues = Array.from({ length: items }, (_, index) => index + 1) const hasPrecision = readOnly && !Number.isInteger(value) const isEligibleForHF = hasPrecision && !highlightOnlySelected const isNotEligibleForHF = hasPrecision && highlightOnlySelected const ratingValue = isNotEligibleForHF ? Math.round(value) : value const isDynamic = !readOnly && !isDisabled const needsDynamicCssVars = ratingValue >= 0.25 const userClassNames = typeof className === 'string' ? className : '' const absoluteHFMode = halfFillMode === HFProps.BOX ? HFProps.BOX : HFProps.SVG const deservesHF = isEligibleForHF && !isGraphicalValueInteger(ratingValue) const shouldRenderReset = !isRequired && !readOnly const tabIndexItems = isRequired ? items : items + 1 const activeStarIndex = isEligibleForHF ? getIntersectionIndex(ratingValues, ratingValue) : ratingValues.indexOf(ratingValue) /* Deps/Callbacks */ const { staticColors, arrayColors, itemShapes, absoluteStrokeWidth, absoluteBoxBorderWidth } = useMemo(() => { const { itemShapes, itemStrokeWidth, boxBorderWidth, ...colors } = itemStyles const userColors =
getColors(colors) return {
itemShapes, absoluteStrokeWidth: getNumber(itemStrokeWidth), absoluteBoxBorderWidth: getNumber(boxBorderWidth), ...userColors, } }, [itemStyles]) const hasArrayColors = Object.keys(arrayColors).length > 0 const getDynamicStyles = useCallback( (starIndex: number, shouldGetCssVars: boolean) => ({ dynamicClassNames: deservesHF ? getHFClassNames(ratingValue, items, absoluteHFMode) : getActiveClassNames(highlightOnlySelected, items, starIndex), dynamicCssVars: shouldGetCssVars && hasArrayColors ? getDynamicCssVars( arrayColors as RequireAtLeastOne<ValidArrayColors>, starIndex, highlightOnlySelected ) : [], }), [ arrayColors, hasArrayColors, highlightOnlySelected, absoluteHFMode, deservesHF, items, ratingValue, ] ) const saveTabIndex = useCallback( () => setTabIndex(getTabIndex(tabIndexItems, activeStarIndex, !isRequired)), [activeStarIndex, tabIndexItems, isRequired] ) /* Refs */ const skipStylesMount = useRef(true) const skipTabMount = useRef(true) const wrapperRef = useRef<HTMLDivElement>(null) const radioRefs = useRef<HTMLDivElement[]>([]) const isRTL = useRef(false) /* State */ const [styles, setStyles] = useState<StylesState>({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) const [tabIndex, setTabIndex] = useState<TabIndex[]>(() => { if (isDynamic) { return getTabIndex(tabIndexItems, activeStarIndex, !isRequired) } return [] }) /* Effects */ useIsomorphicLayoutEffect(() => { if (isDynamic && radioRefs.current) { isRTL.current = isRTLDir(radioRefs.current[0]) } }, [isDynamic]) useEffect(() => { if (!skipStylesMount.current) { return setStyles({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } skipStylesMount.current = false }, [ staticColors, getDynamicStyles, absoluteBoxBorderWidth, activeStarIndex, needsDynamicCssVars, ]) useEffect(() => { if (!skipTabMount.current && isDynamic) { return saveTabIndex() } skipTabMount.current = false }, [isDynamic, saveTabIndex]) /* Log critical errors, return null */ const { shouldRender, reason } = getErrors({ items, itemShapes, }) if (!shouldRender) { console.error(reason) return null } /* Event Handlers */ function handleWhenNeeded( event: FocusEvent | MouseEvent, fromOutsideCallback: () => void, // eslint-disable-next-line @typescript-eslint/no-empty-function fromInsideCallback: () => void = () => {} ) { const fromInside = radioRefs.current.some((radio) => radio === event.relatedTarget) if (!fromInside) { fromOutsideCallback() } else { fromInsideCallback() } } function handleStarLeave() { onHoverChange(0) saveTabIndex() } function handleStarClick(event: MouseEvent, clickedIndex: number) { event.stopPropagation() if (!isRequired && activeStarIndex === clickedIndex) { onChange(0) } else { onChange(clickedIndex + 1) } } function handleMouseEnter(starIndex: number) { onHoverChange(starIndex + 1) setStyles({ ...styles, ...getDynamicStyles(starIndex, true) }) } function handleMouseLeave(event: MouseEvent) { handleWhenNeeded(event, () => { handleStarLeave() }) setStyles({ ...styles, ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } function handleBlur(event: FocusEvent) { handleWhenNeeded(event, () => { handleStarLeave() onBlur() }) } function handleFocus(event: FocusEvent, childIndex: number) { const isResetBtn = !isRequired && childIndex === ratingValues.length const hoveredValue = isResetBtn ? 0 : childIndex + 1 handleWhenNeeded( event, () => { onFocus() onHoverChange(hoveredValue) }, () => { onHoverChange(hoveredValue) } ) } /* Keyboard */ function handleArrowNav(siblingToFocus: number) { setTabIndex(getTabIndex(tabIndexItems, siblingToFocus, !isRequired)) radioRefs.current[siblingToFocus].focus() } function handleKeyDown(event: KeyboardEvent<HTMLDivElement>, childIndex: number) { let siblingToFocus = 0 const lastSibling = isRequired ? ratingValues.length - 1 : ratingValues.length const prevSibling = childIndex - 1 const nextSibling = childIndex + 1 const isResetBtn = !isRequired && childIndex === ratingValues.length const isFiringFromLast = lastSibling === childIndex const isFiringFromFirst = childIndex === 0 const prevToFocus = isFiringFromFirst ? lastSibling : prevSibling const nextToFocus = isFiringFromLast ? 0 : nextSibling switch (event.code) { case 'Shift': case 'Tab': return true case 'ArrowDown': case 'ArrowRight': siblingToFocus = !isRTL.current ? nextToFocus : prevToFocus return handleArrowNav(siblingToFocus) case 'ArrowUp': case 'ArrowLeft': siblingToFocus = !isRTL.current ? prevToFocus : nextToFocus return handleArrowNav(siblingToFocus) case 'Enter': case 'Space': event.preventDefault() return onChange(isResetBtn ? 0 : childIndex + 1) } event.preventDefault() event.stopPropagation() } /* Group props */ const groupClassNames = getGroupClassNames({ className: userClassNames, radius, readOnly, isDisabled, isDynamic, transition, orientation, absoluteBoxBorderWidth, absoluteStrokeWidth, spaceBetween, spaceInside, }) function getAriaGroupProps() { if (!readOnly) { const isAriaRequired = isRequired && !isDisabled const ariaProps: HTMLProps = { role: 'radiogroup', 'aria-required': isAriaRequired, } if (isAriaRequired) { ariaProps['aria-invalid'] = ratingValue <= 0 } if (typeof visibleLabelId === 'string' && visibleLabelId.length > 0) { ariaProps['aria-labelledby'] = visibleLabelId } else { ariaProps['aria-label'] = invisibleLabel } return ariaProps } return { role: 'img', 'aria-label': invisibleLabel, } } function pushGroupRefs(element: HTMLDivElement) { if (isDynamic && !isRequired) { ;(wrapperRef as MutableRef).current = element } if (externalRef) { ;(externalRef as MutableRef).current = element } } /* Radio props */ function getRefs(childIndex: number) { return { ref: (childNode: HTMLDivElement) => (radioRefs.current[childIndex] = childNode), } } function getKeyboardProps(childIndex: number): HTMLProps { return { tabIndex: tabIndex[childIndex], onKeyDown: (event) => handleKeyDown(event, childIndex), } } function getMouseProps(starIndex: number): HTMLProps { return { onClick: (event) => handleStarClick(event, starIndex), onMouseEnter: () => handleMouseEnter(starIndex), onMouseLeave: handleMouseLeave, } } function getAriaRadioProps(starIndex: number): HTMLProps { if (readOnly) { return {} } const labelProps: HTMLProps = {} if (Array.isArray(visibleItemLabelIds)) { labelProps['aria-labelledby'] = visibleItemLabelIds[starIndex] } else { const radioLabels = Array.isArray(invisibleItemLabels) ? invisibleItemLabels : ratingValues.map((_, index: number) => `Rate ${index + 1}`) labelProps['aria-label'] = radioLabels[starIndex] } if (isDisabled) { labelProps['aria-disabled'] = 'true' } return { role: 'radio', 'aria-checked': starIndex + 1 === ratingValue, ...labelProps, } } function getInteractiveRadioProps(starIndex: number): HTMLProps { if (!isDynamic) { return {} } return { ...getRefs(starIndex), ...getKeyboardProps(starIndex), ...getMouseProps(starIndex), onFocus: (event) => handleFocus(event, starIndex), onBlur: (event) => handleBlur(event), } } function getResetProps(childIndex: number): HTMLProps { return { className: RatingClasses.RESET, role: 'radio', 'aria-label': resetLabel, 'aria-checked': ratingValue === 0, onClick: () => onChange(0), onFocus: (event) => { handleFocus(event, childIndex) wrapperRef.current?.classList.add(RatingClasses.GROUP_RESET) }, onBlur: (event) => { handleBlur(event) wrapperRef.current?.classList.remove(RatingClasses.GROUP_RESET) }, ...getResetTestId(), ...getKeyboardProps(childIndex), ...getRefs(childIndex), ...(isDisabled ? { 'aria-disabled': 'true' } : {}), } } /* SVG props */ function getRatingItemProps(starIndex: number): RatingItemProps { const sharedProps = { itemShapes: Array.isArray(itemShapes) ? itemShapes[starIndex] : itemShapes, itemStrokeWidth: absoluteStrokeWidth, orientation, hasHF: false, testId: getSvgTestIds(starIndex), } if (deservesHF && absoluteHFMode === HFProps.SVG) { sharedProps.hasHF = starIndex === activeStarIndex } return sharedProps } /* Render */ return ( <div id={id} className={groupClassNames} style={{ ...style, ...styles.staticCssVars }} ref={pushGroupRefs} {...getAriaGroupProps()} {...devTestId} > {ratingValues.map((value, index) => ( <Fragment key={value}> <div className={`${RatingClasses.BOX} ${styles.dynamicClassNames[index]}`} style={styles.dynamicCssVars[index]} {...getAriaRadioProps(index)} {...getInteractiveRadioProps(index)} {...getRadioTestIds(index)} > <RatingItem {...getRatingItemProps(index)} /> </div> {shouldRenderReset && index === ratingValues.length - 1 && ( <div {...getResetProps(index + 1)} /> )} </Fragment> ))} </div> ) } ) Rating.displayName = 'Rating'
src/Rating.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/RatingItem.tsx", "retrieved_chunk": "import { RatingItemProps, SvgData } from './internalTypes'\nexport function RatingItem({\n itemShapes,\n testId,\n itemStrokeWidth = 0,\n orientation = OrientationProps.HORIZONTAL,\n hasHF = false,\n}: RatingItemProps) {\n const strokeOffset = itemStrokeWidth > 0 ? -(itemStrokeWidth / 2) : 0\n const translateOffset = itemStrokeWidth > 0 ? `${strokeOffset} ${strokeOffset}` : '0 0'", "score": 0.8619226813316345 }, { "filename": "src/getStaticCssVars.ts", "retrieved_chunk": " if (isPositiveNum(boxBorderWidth)) {\n cssVars[ItemVars.BORDER_WIDTH] = `${boxBorderWidth}px`\n }\n const colorsEntries = Object.entries(staticColors)\n if (colorsEntries.length > 0) {\n for (const [key, value] of colorsEntries) {\n setColorCssVars(cssVars, key, value)\n }\n }\n return cssVars", "score": 0.8593240976333618 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": " /** Inactive stroke color of the SVG. */\n inactiveStrokeColor?: string\n /** Inactive background color of the SVG bounding box. */\n inactiveBoxColor?: string\n /** Inactive border color of the SVG bounding box. */\n inactiveBoxBorderColor?: string\n}\nexport type Colors = MaybeArrayColors & NonArrayColors\n/** Custom shapes and colors, visit https://github.com/smastrom/react-rating for more info. */\nexport type ItemStyles = Colors & {", "score": 0.8436782956123352 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " }\n return {}\n }\n function getStrokeAttribute() {\n if (itemStrokeWidth > 0) {\n return {\n strokeWidth: itemStrokeWidth,\n }\n }\n return {}", "score": 0.8350675702095032 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": "import {\n CSSProperties,\n ForwardRefExoticComponent,\n RefAttributes,\n Dispatch,\n SetStateAction,\n} from 'react'\nexport type MaybeArrayColors = {\n /** Active fill color of the SVG, it can be an array of colors in ascending order. */\n activeFillColor?: string | string[]", "score": 0.8342909812927246 } ]
typescript
getColors(colors) return {
import { useRef, useState } from 'react' import { areNum, getNewPosition, getDefsTestId, getUniqueId, toSecondDecimal, useIsomorphicLayoutEffect, } from './utils' import { RatingClasses, OrientationProps } from './constants' import { RatingItemProps, SvgData } from './internalTypes' export function RatingItem({ itemShapes, testId, itemStrokeWidth = 0, orientation = OrientationProps.HORIZONTAL, hasHF = false, }: RatingItemProps) { const strokeOffset = itemStrokeWidth > 0 ? -(itemStrokeWidth / 2) : 0 const translateOffset = itemStrokeWidth > 0 ? `${strokeOffset} ${strokeOffset}` : '0 0' const svgRef = useRef<SVGPathElement | null>(null) const uniqId = useRef<string | null>(null) const [svgData, setSvgData] = useState<SvgData | null>(null) useIsomorphicLayoutEffect(() => { if (hasHF && !uniqId.current) { uniqId.current = `rr_hf_${getUniqueId()}` } if (svgRef.current) { const { width: svgWidth, height: svgHeight, x: svgXPos, y: svgYPos, } = svgRef.current.getBBox() if (areNum(svgWidth, svgHeight, svgXPos, svgYPos)) { const viewBox = `${translateOffset} ${toSecondDecimal( svgWidth + itemStrokeWidth )} ${toSecondDecimal(svgHeight + itemStrokeWidth)}` const translateData = `${getNewPosition(svgXPos)} ${getNewPosition(svgYPos)}` setSvgData({ viewBox, translateData, }) } } }, [itemShapes, itemStrokeWidth, hasHF]) /* Props */ function getHFAttr() { if (hasHF) { return { fill: `url('#${uniqId.current}')`, } } return {} } function getGradientTransformAttr() { if (orientation === OrientationProps.VERTICAL) { return { gradientTransform: 'rotate(90)', } } return {} } function getStrokeAttribute() { if (itemStrokeWidth > 0) { return { strokeWidth: itemStrokeWidth, } } return {} } function getTransform() { if (svgData) { const translateProp = `translate(${svgData?.translateData})` if (translateProp === 'translate(0 0)') { return {} } return { transform: translateProp } } return { transform: undefined } } return ( <svg aria-hidden="true" className={RatingClasses.SVG} xmlns="http://www.w3.org/2000/svg" viewBox={svgData ? svgData.viewBox : '0 0 0 0'} preserveAspectRatio="xMidYMid meet" {...getStrokeAttribute()} {...testId} > {hasHF && uniqId.current && ( <defs {...getDefsTestId()}> <linearGradient id={uniqId.current} {...getGradientTransformAttr()}> <stop className={RatingClasses.DEF_50} offset="50%" /> <
stop className={RatingClasses.DEF_100} offset="50%" /> </linearGradient> </defs> )}
<g ref={svgRef} shapeRendering="geometricPrecision" {...getTransform()} {...getHFAttr()}> {itemShapes} </g> </svg> ) }
src/RatingItem.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/Rating.tsx", "retrieved_chunk": " <div\n className={`${RatingClasses.BOX} ${styles.dynamicClassNames[index]}`}\n style={styles.dynamicCssVars[index]}\n {...getAriaRadioProps(index)}\n {...getInteractiveRadioProps(index)}\n {...getRadioTestIds(index)}\n >\n <RatingItem {...getRatingItemProps(index)} />\n </div>\n {shouldRenderReset && index === ratingValues.length - 1 && (", "score": 0.7418336868286133 }, { "filename": "src/Rating.tsx", "retrieved_chunk": " <div\n id={id}\n className={groupClassNames}\n style={{ ...style, ...styles.staticCssVars }}\n ref={pushGroupRefs}\n {...getAriaGroupProps()}\n {...devTestId}\n >\n {ratingValues.map((value, index) => (\n <Fragment key={value}>", "score": 0.705387532711029 }, { "filename": "src/getGroupClassNames.ts", "retrieved_chunk": " return `${RatingClasses.GROUP} ${orientationClassName} ${strokeClassName} ${borderClassName}\n${transitionClassName} ${radiusClassName} ${cursorClassName} ${disabledClassName} ${gapClassName}\n${paddingClassName} ${className}`\n .replace(/ +/g, ' ')\n .trimEnd()\n}", "score": 0.6278610229492188 }, { "filename": "src/constants.ts", "retrieved_chunk": " DEF_100: 'rr--svg-stop-2',\n}\nexport const ActiveClassNames: Classes = {\n ON: 'rr--on',\n OFF: 'rr--off',\n}\nexport const TransitionClasses: Classes = {\n ZOOM: 'rr--fx-zoom',\n POSITION: 'rr--fx-position',\n OPACITY: 'rr--fx-opacity',", "score": 0.618919849395752 }, { "filename": "src/Rating.tsx", "retrieved_chunk": " onFocus: (event) => {\n handleFocus(event, childIndex)\n wrapperRef.current?.classList.add(RatingClasses.GROUP_RESET)\n },\n onBlur: (event) => {\n handleBlur(event)\n wrapperRef.current?.classList.remove(RatingClasses.GROUP_RESET)\n },\n ...getResetTestId(),\n ...getKeyboardProps(childIndex),", "score": 0.6148319244384766 } ]
typescript
stop className={RatingClasses.DEF_100} offset="50%" /> </linearGradient> </defs> )}
import { request } from "../util/request.util"; import { AppConf } from "../app-conf"; import { Chapter } from "./settings.dao"; //See https://www.meetup.com/api/schema/#p03-objects-section for Meetup API details. /** * Represents all the data that is returned from the Meetup API for an event. */ export type MeetupEvent = { id: string; eventUrl: string; title: string; going: number; imageUrl: string; venue: { name: string; address: string; city: string; state: string; } | null; dateTime: string; group: { id: string; name: string; city: string; state: string; urlname: string; }; description: string; }; /** * The raw response from the Meetup API events query. */ type QueryResponse = { data: Record< string, { upcomingEvents: { edges: Array<{ node: MeetupEvent; }>; }; } | null >; }; /** * Get the events from the Meetup API. */ export async function getMeetupEvents( chapters: Chapter[] ): Promise<Array<MeetupEvent>> { const finalQuery = formQuery(chapters); const response = await request({ name: "Meetup Event", url: `${AppConf.meetupApiBaseUrl}/gql`, method: "POST", headers: { "Content-Type": "application/json" }, body: { query: finalQuery }, }); return processResponse((await response.json()) as QueryResponse); } const eventFragment = "fragment eventFragment on Event { id eventUrl title description going imageUrl venue { name address city state } dateTime group { id name city state urlname}}"; const groupFragment = "fragment groupFragment on Group { upcomingEvents(input:{first:10}) { edges { node { ...eventFragment } } } }"; /** * Form the query to get the events from the Meetup API. * * @param chapters The chapters to get events for. */ function formQuery(chapters: Array<Chapter>): string { let newQuery = "query {"; for (const i in chapters) { newQuery += `result${i
}:groupByUrlname(urlname:"${chapters[i].meetupGroupUrlName}") { ...groupFragment }`;
} newQuery += "}" + eventFragment + groupFragment; return newQuery; } /** * Process the response from the query and return a list of events. * * @param response The response from the query. */ function processResponse(response: QueryResponse): Array<MeetupEvent> { const result = [] as Array<MeetupEvent>; for (const group of Object.values(response.data)) { if (group) { for (const event of group.upcomingEvents.edges) { result.push(event.node); } } } return result; }
src/api/dao/meetup.dao.ts
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": " */\nexport function getEventStats(events: EventsResponse): EventStats {\n const result: EventStats = {\n totalEvents: 0,\n totalActiveChapters: 0,\n totalRSVPs: 0,\n };\n const chapters = new Set<string>();\n events.forEach((event) => {\n result.totalEvents++;", "score": 0.8052064180374146 }, { "filename": "src/api/service/events.service.ts", "retrieved_chunk": "import { getMeetupEvents, MeetupEvent } from \"../dao/meetup.dao\";\nimport { getChapters } from \"../dao/settings.dao\";\n/**\n * Get a list of all upcoming events for Code and Coffee.\n */\nexport async function getEvents(): Promise<Array<MeetupEvent>> {\n const chapters = await getChapters();\n const events = await getMeetupEvents(chapters);\n return events.sort((a, b) => {\n return new Date(a.dateTime).getTime() - new Date(b.dateTime).getTime();", "score": 0.794907808303833 }, { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": "}\nconst chapterRegex = /(?<=\\/info\\/chapter-icons\\/).*$/;\nfunction extractChapter(path: string): string {\n const results = path.match(chapterRegex);\n if (results === null) {\n throw new Error(`Could not extract chapter from path ${path}`);\n }\n return results[0];\n}", "score": 0.7807794809341431 }, { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nexport type EventStats = {\n totalEvents: number;\n totalActiveChapters: number;\n totalRSVPs: number;\n};\n/**\n * Gets the stats for all the current events.\n *\n * @param events The events to get stats from", "score": 0.7770895957946777 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": " name: string;\n github: string;\n email: Array<string>;\n emailTitlePrepend: string;\n};\n/**\n * Get a list of all the Code and Coffee Chapters.\n */\nexport async function getChapters(): Promise<Chapter[]> {\n return (await (", "score": 0.7722666263580322 } ]
typescript
}:groupByUrlname(urlname:"${chapters[i].meetupGroupUrlName}") { ...groupFragment }`;
import { APIGatewayProxyEventV2 } from "aws-lambda"; import { APIGatewayProxyStructuredResultV2 } from "aws-lambda/trigger/api-gateway-proxy"; import { MeetupEvent } from "./dao/meetup.dao"; import { AppConf } from "./app-conf"; import { Controller, routes } from "./routes"; import colors from "colors"; export type EventsResponse = Array<MeetupEvent>; export async function handler( event: APIGatewayProxyEventV2 ): Promise<APIGatewayProxyStructuredResultV2> { try { return await handleRequest(event); } catch (e) { console.error(`Internal server error: ${e}`); return { statusCode: 500, body: JSON.stringify({ message: "Internal server error", requestId: event.requestContext.requestId, }), headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, }; } } async function handleRequest( event: APIGatewayProxyEventV2 ): Promise<APIGatewayProxyStructuredResultV2> { console.log("request received"); if (!isApiKeyValid(event)) { return { statusCode: 401, body: JSON.stringify({ message: "Unauthorized", }), headers: { "Content-Type": "application/json", }, }; } const path = event.requestContext.http.path; const method = event.requestContext.http.method.toUpperCase(); let controller = undefined as undefined | Controller;
for (const route of routes) {
if (method === route.method && new RegExp(`^${route.path}$`).test(path)) { controller = route.controller; break; } } if (controller) { const response = await controller(event); if (!response.headers) { response.headers = {}; } response.headers["Access-Control-Allow-Origin"] = "*"; return response; } console.log( colors.blue("No controller found for path ") + colors.yellow(`"${path}"`) ); return { statusCode: 404, body: JSON.stringify({ message: "Not found", requestId: event.requestContext.requestId, }), headers: { "Content-Type": "application/json", }, }; } const API_KEY_PATH = /^\/api\/.*/; /** * Checks if an API key is needed, and if so, if it is valid. API Keys are required for all non cached requests. * @param request The request to validate. */ function isApiKeyValid(request: APIGatewayProxyEventV2): boolean { if (API_KEY_PATH.test(request.requestContext.http.path)) { return request.headers?.["x-api-key"] === AppConf.apiKey; } return true; }
src/api/index.ts
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": " await getChapterIcon(extractChapter(event.rawPath))\n ).toString(\"base64\"),\n headers: {\n \"Content-Type\": \"image/png\",\n },\n isBase64Encoded: true,\n };\n } catch (e: any | Response) {\n if (e.status === 404) {\n return {", "score": 0.810653567314148 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": "import colors from \"colors\";\nexport type RequestOptions = {\n name: string;\n url: string;\n body?: any;\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n headers?: Record<string, string>;\n};\nexport async function request(options: RequestOptions): Promise<Response> {\n console.info(", "score": 0.8087130784988403 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": " })\n ) +\n \"\\n\"\n );\n let response;\n try {\n response = await fetch(options.url, {\n method: options.method,\n headers: options.headers,\n body: JSON.stringify(options.body),", "score": 0.7913079261779785 }, { "filename": "src/ui/calendar/coffee.dao.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nimport { WebConf } from \"../web-conf\";\n/**\n * Get the details of all events from the Code and Coffee service.\n */\nexport async function getEvents(): Promise<EventsResponse> {\n const response = await fetch(`${WebConf.rootHost}/info/events`, {\n method: \"GET\",\n });\n return response.json();", "score": 0.7768261432647705 }, { "filename": "src/api/routes.ts", "retrieved_chunk": " controller: healthController,\n },\n {\n method: \"GET\",\n path: \"/api/health\",\n controller: healthController,\n },\n {\n method: \"POST\",\n path: \"/api/notify\",", "score": 0.7747907638549805 } ]
typescript
for (const route of routes) {
import { useRef, useState } from 'react' import { areNum, getNewPosition, getDefsTestId, getUniqueId, toSecondDecimal, useIsomorphicLayoutEffect, } from './utils' import { RatingClasses, OrientationProps } from './constants' import { RatingItemProps, SvgData } from './internalTypes' export function RatingItem({ itemShapes, testId, itemStrokeWidth = 0, orientation = OrientationProps.HORIZONTAL, hasHF = false, }: RatingItemProps) { const strokeOffset = itemStrokeWidth > 0 ? -(itemStrokeWidth / 2) : 0 const translateOffset = itemStrokeWidth > 0 ? `${strokeOffset} ${strokeOffset}` : '0 0' const svgRef = useRef<SVGPathElement | null>(null) const uniqId = useRef<string | null>(null) const [svgData, setSvgData] = useState<SvgData | null>(null) useIsomorphicLayoutEffect(() => { if (hasHF && !uniqId.current) { uniqId.current = `rr_hf_${getUniqueId()}` } if (svgRef.current) { const { width: svgWidth, height: svgHeight, x: svgXPos, y: svgYPos, } = svgRef.current.getBBox() if (areNum(svgWidth, svgHeight, svgXPos, svgYPos)) { const viewBox = `${translateOffset} ${toSecondDecimal( svgWidth + itemStrokeWidth )} ${toSecondDecimal(svgHeight + itemStrokeWidth)}` const translateData = `${getNewPosition(svgXPos)} ${getNewPosition(svgYPos)}` setSvgData({ viewBox, translateData, }) } } }, [itemShapes, itemStrokeWidth, hasHF]) /* Props */ function getHFAttr() { if (hasHF) { return { fill: `url('#${uniqId.current}')`, } } return {} } function getGradientTransformAttr() { if (orientation === OrientationProps.VERTICAL) { return { gradientTransform: 'rotate(90)', } } return {} } function getStrokeAttribute() { if (itemStrokeWidth > 0) { return { strokeWidth: itemStrokeWidth, } } return {} } function getTransform() { if (svgData) { const translateProp = `translate(${svgData?.translateData})` if (translateProp === 'translate(0 0)') { return {} } return { transform: translateProp } } return { transform: undefined } } return ( <svg aria-hidden="true" className=
{RatingClasses.SVG}
xmlns="http://www.w3.org/2000/svg" viewBox={svgData ? svgData.viewBox : '0 0 0 0'} preserveAspectRatio="xMidYMid meet" {...getStrokeAttribute()} {...testId} > {hasHF && uniqId.current && ( <defs {...getDefsTestId()}> <linearGradient id={uniqId.current} {...getGradientTransformAttr()}> <stop className={RatingClasses.DEF_50} offset="50%" /> <stop className={RatingClasses.DEF_100} offset="50%" /> </linearGradient> </defs> )} <g ref={svgRef} shapeRendering="geometricPrecision" {...getTransform()} {...getHFAttr()}> {itemShapes} </g> </svg> ) }
src/RatingItem.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/utils.ts", "retrieved_chunk": "export function getRadioTestIds(childIndex: number) {\n if (__DEV__) {\n return { 'data-testid': `rating-child-${childIndex + 1}` }\n } /* c8 ignore next */\n return {}\n}\n/* c8 ignore next */\nexport function getSvgTestIds(childIndex: number) {\n if (__DEV__) {\n return {", "score": 0.7564815282821655 }, { "filename": "src/Rating.tsx", "retrieved_chunk": " onBlur: (event) => handleBlur(event),\n }\n }\n function getResetProps(childIndex: number): HTMLProps {\n return {\n className: RatingClasses.RESET,\n role: 'radio',\n 'aria-label': resetLabel,\n 'aria-checked': ratingValue === 0,\n onClick: () => onChange(0),", "score": 0.7556126117706299 }, { "filename": "src/Rating.tsx", "retrieved_chunk": " ...getRefs(childIndex),\n ...(isDisabled ? { 'aria-disabled': 'true' } : {}),\n }\n }\n /* SVG props */\n function getRatingItemProps(starIndex: number): RatingItemProps {\n const sharedProps = {\n itemShapes: Array.isArray(itemShapes) ? itemShapes[starIndex] : itemShapes,\n itemStrokeWidth: absoluteStrokeWidth,\n orientation,", "score": 0.7488924860954285 }, { "filename": "src/getStaticClassNames.ts", "retrieved_chunk": " case TransitionProps.COLORS:\n return TransitionClasses.COLORS\n default:\n return ''\n }\n}\n/* c8 ignore stop */\n/* c8 ignore start */\nexport function getRadiusClassName(radiusProp: unknown): MaybeEmptyClassName {\n switch (radiusProp) {", "score": 0.7472704648971558 }, { "filename": "src/Rating.tsx", "retrieved_chunk": " <div\n id={id}\n className={groupClassNames}\n style={{ ...style, ...styles.staticCssVars }}\n ref={pushGroupRefs}\n {...getAriaGroupProps()}\n {...devTestId}\n >\n {ratingValues.map((value, index) => (\n <Fragment key={value}>", "score": 0.7379993200302124 } ]
typescript
{RatingClasses.SVG}
import { forwardRef, useMemo, useCallback, useRef, useState, useEffect, Fragment, KeyboardEvent, } from 'react' import { RatingItem } from './RatingItem' import { getDynamicCssVars } from './getDynamicCssVars' import { getGroupClassNames } from './getGroupClassNames' import { getActiveClassNames } from './getActiveClassNames' import { getHFClassNames } from './getHFClassNames' import { getStaticCssVars } from './getStaticCssVars' import { getColors } from './getColors' import { getTabIndex } from './getTabIndex' import { getErrors } from './getErrors' import { getIntersectionIndex, getNumber, getRadioTestIds, getSvgTestIds, devTestId, getResetTestId, isGraphicalValueInteger, isRTLDir, useIsomorphicLayoutEffect, noop, } from './utils' import { Sizes, OrientationProps, TransitionProps, HFProps, RatingClasses } from './constants' import { defaultItemStyles } from './defaultItemStyles' import { RatingProps, Rating as RatingComponent } from './exportedTypes' import { StylesState, RequireAtLeastOne, ValidArrayColors, TabIndex, RatingItemProps, MouseEvent, FocusEvent, HTMLProps, MutableRef, } from './internalTypes' /** Thank you for using **React Rating**. * Visit https://github.com/smastrom/react-rating to read the full documentation. */ export const Rating: typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>( ( { value, items = 5, readOnly = false, onChange = noop, onHoverChange = noop, onFocus = noop, onBlur = noop, isDisabled = false, highlightOnlySelected = false, orientation = OrientationProps.HORIZONTAL, spaceBetween = Sizes.NONE, spaceInside = Sizes.SMALL, radius = Sizes.NONE, transition = TransitionProps.COLORS, itemStyles = defaultItemStyles, isRequired = false, halfFillMode = HFProps.SVG, visibleLabelId, visibleItemLabelIds, invisibleItemLabels, invisibleLabel = readOnly ? value > 0 ? `Rated ${value} on ${items}` : 'Not rated' : 'Rating Selection', resetLabel = 'Reset rating', id, className, style, }, externalRef ) => { /* Helpers */ const ratingValues = Array.from({ length: items }, (_, index) => index + 1) const hasPrecision = readOnly && !Number.isInteger(value) const isEligibleForHF = hasPrecision && !highlightOnlySelected const isNotEligibleForHF = hasPrecision && highlightOnlySelected const ratingValue = isNotEligibleForHF ? Math.round(value) : value const isDynamic = !readOnly && !isDisabled const needsDynamicCssVars = ratingValue >= 0.25 const userClassNames = typeof className === 'string' ? className : '' const absoluteHFMode = halfFillMode === HFProps.BOX ? HFProps.BOX : HFProps.SVG const deservesHF = isEligibleForHF && !isGraphicalValueInteger(ratingValue) const shouldRenderReset = !isRequired && !readOnly const tabIndexItems = isRequired ? items : items + 1 const activeStarIndex = isEligibleForHF ? getIntersectionIndex(ratingValues, ratingValue) : ratingValues.indexOf(ratingValue) /* Deps/Callbacks */ const { staticColors, arrayColors, itemShapes, absoluteStrokeWidth, absoluteBoxBorderWidth } = useMemo(() => { const { itemShapes, itemStrokeWidth, boxBorderWidth, ...colors } = itemStyles const userColors = getColors(colors) return { itemShapes, absoluteStrokeWidth: getNumber(itemStrokeWidth), absoluteBoxBorderWidth: getNumber(boxBorderWidth), ...userColors, } }, [itemStyles]) const hasArrayColors = Object.keys(arrayColors).length > 0 const getDynamicStyles = useCallback( (starIndex: number, shouldGetCssVars: boolean) => ({ dynamicClassNames: deservesHF ? getHFClassNames(ratingValue, items, absoluteHFMode) : getActiveClassNames(highlightOnlySelected, items, starIndex), dynamicCssVars: shouldGetCssVars && hasArrayColors ? getDynamicCssVars( arrayColors as RequireAtLeastOne<ValidArrayColors>, starIndex, highlightOnlySelected ) : [], }), [ arrayColors, hasArrayColors, highlightOnlySelected, absoluteHFMode, deservesHF, items, ratingValue, ] ) const saveTabIndex = useCallback( () => setTabIndex(getTabIndex(tabIndexItems, activeStarIndex, !isRequired)), [activeStarIndex, tabIndexItems, isRequired] ) /* Refs */ const skipStylesMount = useRef(true) const skipTabMount = useRef(true) const wrapperRef = useRef<HTMLDivElement>(null) const radioRefs = useRef<HTMLDivElement[]>([]) const isRTL = useRef(false) /* State */ const [styles, setStyles] = useState<StylesState>({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) const [tabIndex, setTabIndex] = useState<TabIndex[]>(() => { if (isDynamic) { return getTabIndex(tabIndexItems, activeStarIndex, !isRequired) } return [] }) /* Effects */ useIsomorphicLayoutEffect(() => { if (isDynamic && radioRefs.current) { isRTL.current = isRTLDir(radioRefs.current[0]) } }, [isDynamic]) useEffect(() => { if (!skipStylesMount.current) { return setStyles({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } skipStylesMount.current = false }, [ staticColors, getDynamicStyles, absoluteBoxBorderWidth, activeStarIndex, needsDynamicCssVars, ]) useEffect(() => { if (!skipTabMount.current && isDynamic) { return saveTabIndex() } skipTabMount.current = false }, [isDynamic, saveTabIndex]) /* Log critical errors, return null */ const { shouldRender, reason
} = getErrors({
items, itemShapes, }) if (!shouldRender) { console.error(reason) return null } /* Event Handlers */ function handleWhenNeeded( event: FocusEvent | MouseEvent, fromOutsideCallback: () => void, // eslint-disable-next-line @typescript-eslint/no-empty-function fromInsideCallback: () => void = () => {} ) { const fromInside = radioRefs.current.some((radio) => radio === event.relatedTarget) if (!fromInside) { fromOutsideCallback() } else { fromInsideCallback() } } function handleStarLeave() { onHoverChange(0) saveTabIndex() } function handleStarClick(event: MouseEvent, clickedIndex: number) { event.stopPropagation() if (!isRequired && activeStarIndex === clickedIndex) { onChange(0) } else { onChange(clickedIndex + 1) } } function handleMouseEnter(starIndex: number) { onHoverChange(starIndex + 1) setStyles({ ...styles, ...getDynamicStyles(starIndex, true) }) } function handleMouseLeave(event: MouseEvent) { handleWhenNeeded(event, () => { handleStarLeave() }) setStyles({ ...styles, ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } function handleBlur(event: FocusEvent) { handleWhenNeeded(event, () => { handleStarLeave() onBlur() }) } function handleFocus(event: FocusEvent, childIndex: number) { const isResetBtn = !isRequired && childIndex === ratingValues.length const hoveredValue = isResetBtn ? 0 : childIndex + 1 handleWhenNeeded( event, () => { onFocus() onHoverChange(hoveredValue) }, () => { onHoverChange(hoveredValue) } ) } /* Keyboard */ function handleArrowNav(siblingToFocus: number) { setTabIndex(getTabIndex(tabIndexItems, siblingToFocus, !isRequired)) radioRefs.current[siblingToFocus].focus() } function handleKeyDown(event: KeyboardEvent<HTMLDivElement>, childIndex: number) { let siblingToFocus = 0 const lastSibling = isRequired ? ratingValues.length - 1 : ratingValues.length const prevSibling = childIndex - 1 const nextSibling = childIndex + 1 const isResetBtn = !isRequired && childIndex === ratingValues.length const isFiringFromLast = lastSibling === childIndex const isFiringFromFirst = childIndex === 0 const prevToFocus = isFiringFromFirst ? lastSibling : prevSibling const nextToFocus = isFiringFromLast ? 0 : nextSibling switch (event.code) { case 'Shift': case 'Tab': return true case 'ArrowDown': case 'ArrowRight': siblingToFocus = !isRTL.current ? nextToFocus : prevToFocus return handleArrowNav(siblingToFocus) case 'ArrowUp': case 'ArrowLeft': siblingToFocus = !isRTL.current ? prevToFocus : nextToFocus return handleArrowNav(siblingToFocus) case 'Enter': case 'Space': event.preventDefault() return onChange(isResetBtn ? 0 : childIndex + 1) } event.preventDefault() event.stopPropagation() } /* Group props */ const groupClassNames = getGroupClassNames({ className: userClassNames, radius, readOnly, isDisabled, isDynamic, transition, orientation, absoluteBoxBorderWidth, absoluteStrokeWidth, spaceBetween, spaceInside, }) function getAriaGroupProps() { if (!readOnly) { const isAriaRequired = isRequired && !isDisabled const ariaProps: HTMLProps = { role: 'radiogroup', 'aria-required': isAriaRequired, } if (isAriaRequired) { ariaProps['aria-invalid'] = ratingValue <= 0 } if (typeof visibleLabelId === 'string' && visibleLabelId.length > 0) { ariaProps['aria-labelledby'] = visibleLabelId } else { ariaProps['aria-label'] = invisibleLabel } return ariaProps } return { role: 'img', 'aria-label': invisibleLabel, } } function pushGroupRefs(element: HTMLDivElement) { if (isDynamic && !isRequired) { ;(wrapperRef as MutableRef).current = element } if (externalRef) { ;(externalRef as MutableRef).current = element } } /* Radio props */ function getRefs(childIndex: number) { return { ref: (childNode: HTMLDivElement) => (radioRefs.current[childIndex] = childNode), } } function getKeyboardProps(childIndex: number): HTMLProps { return { tabIndex: tabIndex[childIndex], onKeyDown: (event) => handleKeyDown(event, childIndex), } } function getMouseProps(starIndex: number): HTMLProps { return { onClick: (event) => handleStarClick(event, starIndex), onMouseEnter: () => handleMouseEnter(starIndex), onMouseLeave: handleMouseLeave, } } function getAriaRadioProps(starIndex: number): HTMLProps { if (readOnly) { return {} } const labelProps: HTMLProps = {} if (Array.isArray(visibleItemLabelIds)) { labelProps['aria-labelledby'] = visibleItemLabelIds[starIndex] } else { const radioLabels = Array.isArray(invisibleItemLabels) ? invisibleItemLabels : ratingValues.map((_, index: number) => `Rate ${index + 1}`) labelProps['aria-label'] = radioLabels[starIndex] } if (isDisabled) { labelProps['aria-disabled'] = 'true' } return { role: 'radio', 'aria-checked': starIndex + 1 === ratingValue, ...labelProps, } } function getInteractiveRadioProps(starIndex: number): HTMLProps { if (!isDynamic) { return {} } return { ...getRefs(starIndex), ...getKeyboardProps(starIndex), ...getMouseProps(starIndex), onFocus: (event) => handleFocus(event, starIndex), onBlur: (event) => handleBlur(event), } } function getResetProps(childIndex: number): HTMLProps { return { className: RatingClasses.RESET, role: 'radio', 'aria-label': resetLabel, 'aria-checked': ratingValue === 0, onClick: () => onChange(0), onFocus: (event) => { handleFocus(event, childIndex) wrapperRef.current?.classList.add(RatingClasses.GROUP_RESET) }, onBlur: (event) => { handleBlur(event) wrapperRef.current?.classList.remove(RatingClasses.GROUP_RESET) }, ...getResetTestId(), ...getKeyboardProps(childIndex), ...getRefs(childIndex), ...(isDisabled ? { 'aria-disabled': 'true' } : {}), } } /* SVG props */ function getRatingItemProps(starIndex: number): RatingItemProps { const sharedProps = { itemShapes: Array.isArray(itemShapes) ? itemShapes[starIndex] : itemShapes, itemStrokeWidth: absoluteStrokeWidth, orientation, hasHF: false, testId: getSvgTestIds(starIndex), } if (deservesHF && absoluteHFMode === HFProps.SVG) { sharedProps.hasHF = starIndex === activeStarIndex } return sharedProps } /* Render */ return ( <div id={id} className={groupClassNames} style={{ ...style, ...styles.staticCssVars }} ref={pushGroupRefs} {...getAriaGroupProps()} {...devTestId} > {ratingValues.map((value, index) => ( <Fragment key={value}> <div className={`${RatingClasses.BOX} ${styles.dynamicClassNames[index]}`} style={styles.dynamicCssVars[index]} {...getAriaRadioProps(index)} {...getInteractiveRadioProps(index)} {...getRadioTestIds(index)} > <RatingItem {...getRatingItemProps(index)} /> </div> {shouldRenderReset && index === ratingValues.length - 1 && ( <div {...getResetProps(index + 1)} /> )} </Fragment> ))} </div> ) } ) Rating.displayName = 'Rating'
src/Rating.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/getTabIndex.ts", "retrieved_chunk": "import { TabIndex } from './internalTypes'\nexport function getTabIndex(items: number, selectedIndex: number, hasReset = false): TabIndex[] {\n return Array.from({ length: items }, (_, index) => {\n if (hasReset && selectedIndex < 0) {\n if (index === items - 1) {\n return 0\n }\n return -1\n }\n if (selectedIndex <= 0) {", "score": 0.8155030012130737 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " }\n function getTransform() {\n if (svgData) {\n const translateProp = `translate(${svgData?.translateData})`\n if (translateProp === 'translate(0 0)') {\n return {}\n }\n return { transform: translateProp }\n }\n return { transform: undefined }", "score": 0.7810059785842896 }, { "filename": "src/getErrors.ts", "retrieved_chunk": " const errorsObj: ErrorObj = { shouldRender: true, reason: '' }\n if (typeof items !== 'number' || items < 1 || items > 10) {\n return setErrors(errorsObj, 'items is invalid')\n }\n if (!itemShapes) {\n return setErrors(errorsObj, 'itemStyles needs at least the property itemShapes set')\n }\n if (!Array.isArray(itemShapes) && !isValidElement(itemShapes as object | null | undefined)) {\n return setErrors(errorsObj, invalidJSXMsg)\n }", "score": 0.7785080075263977 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " fill: `url('#${uniqId.current}')`,\n }\n }\n return {}\n }\n function getGradientTransformAttr() {\n if (orientation === OrientationProps.VERTICAL) {\n return {\n gradientTransform: 'rotate(90)',\n }", "score": 0.7605048418045044 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " }\n return {}\n }\n function getStrokeAttribute() {\n if (itemStrokeWidth > 0) {\n return {\n strokeWidth: itemStrokeWidth,\n }\n }\n return {}", "score": 0.7598631381988525 } ]
typescript
} = getErrors({
import { useRef, useState } from 'react' import { areNum, getNewPosition, getDefsTestId, getUniqueId, toSecondDecimal, useIsomorphicLayoutEffect, } from './utils' import { RatingClasses, OrientationProps } from './constants' import { RatingItemProps, SvgData } from './internalTypes' export function RatingItem({ itemShapes, testId, itemStrokeWidth = 0, orientation = OrientationProps.HORIZONTAL, hasHF = false, }: RatingItemProps) { const strokeOffset = itemStrokeWidth > 0 ? -(itemStrokeWidth / 2) : 0 const translateOffset = itemStrokeWidth > 0 ? `${strokeOffset} ${strokeOffset}` : '0 0' const svgRef = useRef<SVGPathElement | null>(null) const uniqId = useRef<string | null>(null) const [svgData, setSvgData] = useState<SvgData | null>(null) useIsomorphicLayoutEffect(() => { if (hasHF && !uniqId.current) { uniqId.current = `rr_hf_${getUniqueId()}` } if (svgRef.current) { const { width: svgWidth, height: svgHeight, x: svgXPos, y: svgYPos, } = svgRef.current.getBBox() if (areNum(svgWidth, svgHeight, svgXPos, svgYPos)) { const viewBox = `${translateOffset} ${toSecondDecimal( svgWidth + itemStrokeWidth )} ${toSecondDecimal(svgHeight + itemStrokeWidth)}` const translateData = `${getNewPosition(svgXPos)} ${getNewPosition(svgYPos)}` setSvgData({ viewBox, translateData, }) } } }, [itemShapes, itemStrokeWidth, hasHF]) /* Props */ function getHFAttr() { if (hasHF) { return { fill: `url('#${uniqId.current}')`, } } return {} } function getGradientTransformAttr() { if (orientation
=== OrientationProps.VERTICAL) {
return { gradientTransform: 'rotate(90)', } } return {} } function getStrokeAttribute() { if (itemStrokeWidth > 0) { return { strokeWidth: itemStrokeWidth, } } return {} } function getTransform() { if (svgData) { const translateProp = `translate(${svgData?.translateData})` if (translateProp === 'translate(0 0)') { return {} } return { transform: translateProp } } return { transform: undefined } } return ( <svg aria-hidden="true" className={RatingClasses.SVG} xmlns="http://www.w3.org/2000/svg" viewBox={svgData ? svgData.viewBox : '0 0 0 0'} preserveAspectRatio="xMidYMid meet" {...getStrokeAttribute()} {...testId} > {hasHF && uniqId.current && ( <defs {...getDefsTestId()}> <linearGradient id={uniqId.current} {...getGradientTransformAttr()}> <stop className={RatingClasses.DEF_50} offset="50%" /> <stop className={RatingClasses.DEF_100} offset="50%" /> </linearGradient> </defs> )} <g ref={svgRef} shapeRendering="geometricPrecision" {...getTransform()} {...getHFAttr()}> {itemShapes} </g> </svg> ) }
src/RatingItem.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/Rating.tsx", "retrieved_chunk": " event.preventDefault()\n return onChange(isResetBtn ? 0 : childIndex + 1)\n }\n event.preventDefault()\n event.stopPropagation()\n }\n /* Group props */\n const groupClassNames = getGroupClassNames({\n className: userClassNames,\n radius,", "score": 0.8249920606613159 }, { "filename": "src/getStaticClassNames.ts", "retrieved_chunk": " case TransitionProps.COLORS:\n return TransitionClasses.COLORS\n default:\n return ''\n }\n}\n/* c8 ignore stop */\n/* c8 ignore start */\nexport function getRadiusClassName(radiusProp: unknown): MaybeEmptyClassName {\n switch (radiusProp) {", "score": 0.8159564733505249 }, { "filename": "src/getStaticCssVars.ts", "retrieved_chunk": " if (isPositiveNum(boxBorderWidth)) {\n cssVars[ItemVars.BORDER_WIDTH] = `${boxBorderWidth}px`\n }\n const colorsEntries = Object.entries(staticColors)\n if (colorsEntries.length > 0) {\n for (const [key, value] of colorsEntries) {\n setColorCssVars(cssVars, key, value)\n }\n }\n return cssVars", "score": 0.8106613159179688 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": "import {\n CSSProperties,\n ForwardRefExoticComponent,\n RefAttributes,\n Dispatch,\n SetStateAction,\n} from 'react'\nexport type MaybeArrayColors = {\n /** Active fill color of the SVG, it can be an array of colors in ascending order. */\n activeFillColor?: string | string[]", "score": 0.8065057992935181 }, { "filename": "src/setColorCssVars.ts", "retrieved_chunk": "/* c8 ignore next */\nexport function setColorCssVars(targetObj: CSSVariables, key: string, value: string) {\n const isActive = setDyamicCssVars(targetObj, key, value)\n if (!isActive) {\n switch (key) {\n case InactiveColorProps.FILL:\n targetObj[InactiveVars.FILL] = value\n break\n case InactiveColorProps.BOX:\n targetObj[InactiveVars.BOX] = value", "score": 0.8058599233627319 } ]
typescript
=== OrientationProps.VERTICAL) {
import React, { useEffect, useState } from "react"; import { CoffeeEvent } from "./coffee-event"; import styled from "styled-components"; import { getEvents } from "./coffee.dao"; import { EventStats, getEventStats } from "./events.util"; import { CoffeeEventStats } from "./coffee-event-stats"; const CalendarContainer = styled.div` display: flex; flex-direction: column; height: ${({ height }: { height: number }) => height}px; padding: 15px; border-radius: 20px; box-shadow: 3px 3px 33px rgba(0, 0, 0, 0.04); @media (max-width: 600px) { padding: 0; } `; const EventTitle = styled.h1` @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap"); font-family: "Cormorant Garamond", serif; font-weight: 700; font-size: 36px; margin: 0 0 10px 0; `; const EventHolder = styled.div` border-top: 1px solid #dcdcdc; border-bottom: 1px solid #dcdcdc; overflow-y: scroll; padding-right: 20px; display: flex; flex-direction: column; align-items: center; /* width */ ::-webkit-scrollbar { width: 10px; transform: rotate(180deg); } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d4b9ff; border: 1px solid black; border-radius: 2px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #dbc4ff; border: 2px solid black; border-radius: 2px; } `; export function CoffeeCalendar({ height }: { height: number }) { const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>); const [showStats, setShowStats] = useState(false as boolean); const [stats, setStats] = useState(undefined as undefined | EventStats); useEffect(() => { getEvents().then((events) => { const newCoffeeEvents = [] as Array<JSX.Element>; for (const event of events) { if (event) { newCoffeeEvents.push(<CoffeeEvent event={event} key={event.id} />); } } setCoffeeEvents(newCoffeeEvents);
setStats(getEventStats(events));
}); }, []); useEffect(() => { function displayDialogListener(event: KeyboardEvent): void { if (event.code === "KeyI" && event.ctrlKey) { setShowStats(!showStats); } } document.addEventListener("keydown", displayDialogListener); return () => { document.removeEventListener("keydown", displayDialogListener); }; }, [showStats]); return ( <CalendarContainer height={height}> <EventTitle>Events</EventTitle> {showStats && stats && <CoffeeEventStats stats={stats} />} <EventHolder>{coffeeEvents}</EventHolder> </CalendarContainer> ); }
src/ui/calendar/coffee-calendar.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " * @param response The response from the query.\n */\nfunction processResponse(response: QueryResponse): Array<MeetupEvent> {\n const result = [] as Array<MeetupEvent>;\n for (const group of Object.values(response.data)) {\n if (group) {\n for (const event of group.upcomingEvents.edges) {\n result.push(event.node);\n }\n }", "score": 0.7565010786056519 }, { "filename": "src/ui/calendar/coffee-event-stats.tsx", "retrieved_chunk": "`;\nexport function CoffeeEventStats({ stats }: { stats: EventStats }) {\n return (\n <StatsContainer>\n <Stat>Events: {stats.totalEvents}</Stat>\n <Stat>RSVPS: {stats.totalRSVPs}</Stat>\n <Stat>Active Chapters: {stats.totalActiveChapters}</Stat>\n </StatsContainer>\n );\n}", "score": 0.7162892818450928 }, { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": "const EVENT_DESCRIPTION_LENGTH = 125;\nexport function CoffeeEvent({ event }: { event: MeetupEvent }) {\n const [iconImage, setIconImage] = useState(\n undefined as undefined | ReactNode\n );\n const [smallIconImage, setSmallIconImage] = useState(\n undefined as undefined | ReactNode\n );\n function rsvpAction() {\n window.open(event.eventUrl, \"_blank\");", "score": 0.7141228318214417 }, { "filename": "src/api/service/events.service.ts", "retrieved_chunk": "import { getMeetupEvents, MeetupEvent } from \"../dao/meetup.dao\";\nimport { getChapters } from \"../dao/settings.dao\";\n/**\n * Get a list of all upcoming events for Code and Coffee.\n */\nexport async function getEvents(): Promise<Array<MeetupEvent>> {\n const chapters = await getChapters();\n const events = await getMeetupEvents(chapters);\n return events.sort((a, b) => {\n return new Date(a.dateTime).getTime() - new Date(b.dateTime).getTime();", "score": 0.7108215093612671 }, { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": " */\nexport function getEventStats(events: EventsResponse): EventStats {\n const result: EventStats = {\n totalEvents: 0,\n totalActiveChapters: 0,\n totalRSVPs: 0,\n };\n const chapters = new Set<string>();\n events.forEach((event) => {\n result.totalEvents++;", "score": 0.7058271169662476 } ]
typescript
setStats(getEventStats(events));
import { CSSClassName, CSSVariable } from './internalTypes' import { Orientation, HF, Sizes as SizesT, Transitions, MaybeArrayColors, NonArrayColors, } from './exportedTypes' /* ClassNames */ type Classes = { [key: string]: CSSClassName } export const RatingClasses: Classes = { GROUP: 'rr--group', BOX: 'rr--box', SVG: 'rr--svg', RESET: 'rr--reset', GROUP_RESET: 'rr--focus-reset', DEF_50: 'rr--svg-stop-1', DEF_100: 'rr--svg-stop-2', } export const ActiveClassNames: Classes = { ON: 'rr--on', OFF: 'rr--off', } export const TransitionClasses: Classes = { ZOOM: 'rr--fx-zoom', POSITION: 'rr--fx-position', OPACITY: 'rr--fx-opacity', COLORS: 'rr--fx-colors', } export const RadiusClasses: Classes = { SMALL: 'rr--rx-sm', MEDIUM: 'rr--rx-md', LARGE: 'rr--rx-lg', FULL: 'rr--rx-full', } export const GapClasses: Classes = { SMALL: 'rr--gap-sm', MEDIUM: 'rr--gap-md', LARGE: 'rr--gap-lg', } export const PaddingClasses: Classes = { SMALL: 'rr--space-sm', MEDIUM: 'rr--space-md', LARGE: 'rr--space-lg', } export const CursorClasses: Classes = { POINTER: 'rr--pointer', DISABLED: 'rr--disabled', } export const OrientationClasses: Classes = { VERTICAL: 'rr--dir-y', HORIZONTAL: 'rr--dir-x', } export const HasClasses: Classes = { STROKE: 'rr--has-stroke', BORDER: 'rr--has-border', } export const HFClasses: Classes = { BOX_ON: 'rr--hf-box-on', BOX_INT: 'rr--hf-box-int', BOX_OFF: 'rr--hf-box-off', SVG_ON: 'rr--hf-svg-on', SVG_OFF: 'rr--hf-svg-off', } /* Variables */ type Variables = {
[key: string]: CSSVariable }
export const ActiveVars: Variables = { FILL: '--rr--fill-on-color', BOX: '--rr--box-on-color', BORDER: '--rr--border-on-color', STROKE: '--rr--stroke-on-color', } export const InactiveVars: Variables = { FILL: '--rr--fill-off-color', BOX: '--rr--box-off-color', BORDER: '--rr--border-off-color', STROKE: '--rr--stroke-off-color', } export const ItemVars: Variables = { BORDER_WIDTH: '--rr--border-width', } /* Props */ type ValuesFromUnion<T> = { [key: string]: T } export const OrientationProps: ValuesFromUnion<Orientation> = { HORIZONTAL: 'horizontal', VERTICAL: 'vertical', } export const HFProps: ValuesFromUnion<HF> = { SVG: 'svg', BOX: 'box', } export const Sizes: ValuesFromUnion<SizesT> = { NONE: 'none', SMALL: 'small', MEDIUM: 'medium', LARGE: 'large', FULL: 'full', } export const TransitionProps: ValuesFromUnion<Transitions> = { NONE: 'none', ZOOM: 'zoom', POSITION: 'position', OPACITY: 'opacity', COLORS: 'colors', } /* Color Props */ type ValuesFromKeys<T> = { [key: string]: keyof T } export const ActiveColorProps: ValuesFromKeys<MaybeArrayColors> = { FILL: 'activeFillColor', BOX: 'activeBoxColor', BORDER: 'activeBoxBorderColor', STROKE: 'activeStrokeColor', } export const InactiveColorProps: ValuesFromKeys<NonArrayColors> = { FILL: 'inactiveFillColor', BOX: 'inactiveBoxColor', BORDER: 'inactiveBoxBorderColor', STROKE: 'inactiveStrokeColor', }
src/constants.ts
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/internalTypes.ts", "retrieved_chunk": "import { ItemStyles, MaybeArrayColors, NonArrayColors, RatingProps } from './exportedTypes'\ntype CSSPrefix = 'rr'\nexport type CSSVariable = `--${CSSPrefix}--${string}`\nexport type CSSVariables = {\n [key: CSSVariable]: string\n}\nexport type CSSClassName = `${CSSPrefix}--${string}`\nexport type TagID = `${CSSPrefix}_${string}`\nexport type MaybeEmptyClassName = CSSClassName | ''\ntype Colors<T> = {", "score": 0.6183513402938843 }, { "filename": "src/utils.ts", "retrieved_chunk": " 'data-testid': `rating-child-svg-${childIndex + 1}`,\n }\n } /* c8 ignore next */\n return {}\n}\n/* c8 ignore next */\nexport function getDefsTestId() {\n if (__DEV__) {\n return {\n 'data-testid': 'svg-defs-testid',", "score": 0.5988104343414307 }, { "filename": "src/defaultItemStyles.ts", "retrieved_chunk": "import { Star } from './Shapes'\nimport { ItemStyles } from './exportedTypes'\nexport const defaultItemStyles: ItemStyles = {\n itemShapes: Star,\n itemStrokeWidth: 2,\n activeFillColor: '#ffb23f',\n inactiveFillColor: '#fff7ed',\n activeStrokeColor: '#e17b21',\n inactiveStrokeColor: '#eda76a',\n}", "score": 0.5820177793502808 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " const svgRef = useRef<SVGPathElement | null>(null)\n const uniqId = useRef<string | null>(null)\n const [svgData, setSvgData] = useState<SvgData | null>(null)\n useIsomorphicLayoutEffect(() => {\n if (hasHF && !uniqId.current) {\n uniqId.current = `rr_hf_${getUniqueId()}`\n }\n if (svgRef.current) {\n const {\n width: svgWidth,", "score": 0.5621118545532227 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": " /** JSX element to render the inner shapes of the SVG.\n * Visit https://github.com/smastrom/react-rating#how-to-create-itemshapes-elements for more info. */\n itemShapes: JSX.Element | JSX.Element[]\n /** Stroke width of the SVG, expressed in viewBox user coordinate's unit size. */\n itemStrokeWidth?: number\n /** Border width of the SVG bounding box, expressed with an integer representing the pixels. */\n boxBorderWidth?: number\n}\nexport type Orientation = 'horizontal' | 'vertical'\nexport type Sizes = 'none' | 'small' | 'medium' | 'large' | 'full'", "score": 0.5611386895179749 } ]
typescript
[key: string]: CSSVariable }
import { request } from "../util/request.util"; import { AppConf } from "../app-conf"; import { Chapter } from "./settings.dao"; //See https://www.meetup.com/api/schema/#p03-objects-section for Meetup API details. /** * Represents all the data that is returned from the Meetup API for an event. */ export type MeetupEvent = { id: string; eventUrl: string; title: string; going: number; imageUrl: string; venue: { name: string; address: string; city: string; state: string; } | null; dateTime: string; group: { id: string; name: string; city: string; state: string; urlname: string; }; description: string; }; /** * The raw response from the Meetup API events query. */ type QueryResponse = { data: Record< string, { upcomingEvents: { edges: Array<{ node: MeetupEvent; }>; }; } | null >; }; /** * Get the events from the Meetup API. */ export async function getMeetupEvents( chapters: Chapter[] ): Promise<Array<MeetupEvent>> { const finalQuery = formQuery(chapters);
const response = await request({
name: "Meetup Event", url: `${AppConf.meetupApiBaseUrl}/gql`, method: "POST", headers: { "Content-Type": "application/json" }, body: { query: finalQuery }, }); return processResponse((await response.json()) as QueryResponse); } const eventFragment = "fragment eventFragment on Event { id eventUrl title description going imageUrl venue { name address city state } dateTime group { id name city state urlname}}"; const groupFragment = "fragment groupFragment on Group { upcomingEvents(input:{first:10}) { edges { node { ...eventFragment } } } }"; /** * Form the query to get the events from the Meetup API. * * @param chapters The chapters to get events for. */ function formQuery(chapters: Array<Chapter>): string { let newQuery = "query {"; for (const i in chapters) { newQuery += `result${i}:groupByUrlname(urlname:"${chapters[i].meetupGroupUrlName}") { ...groupFragment }`; } newQuery += "}" + eventFragment + groupFragment; return newQuery; } /** * Process the response from the query and return a list of events. * * @param response The response from the query. */ function processResponse(response: QueryResponse): Array<MeetupEvent> { const result = [] as Array<MeetupEvent>; for (const group of Object.values(response.data)) { if (group) { for (const event of group.upcomingEvents.edges) { result.push(event.node); } } } return result; }
src/api/dao/meetup.dao.ts
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/service/events.service.ts", "retrieved_chunk": "import { getMeetupEvents, MeetupEvent } from \"../dao/meetup.dao\";\nimport { getChapters } from \"../dao/settings.dao\";\n/**\n * Get a list of all upcoming events for Code and Coffee.\n */\nexport async function getEvents(): Promise<Array<MeetupEvent>> {\n const chapters = await getChapters();\n const events = await getMeetupEvents(chapters);\n return events.sort((a, b) => {\n return new Date(a.dateTime).getTime() - new Date(b.dateTime).getTime();", "score": 0.8474528789520264 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": "}\n/**\n * Get all the notification settings.\n */\nexport async function getNotificationSettings(): Promise<\n Array<NotificationSetting>\n> {\n return await (\n await request({\n name: \"Notification Settings\",", "score": 0.8136640191078186 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": " name: string;\n github: string;\n email: Array<string>;\n emailTitlePrepend: string;\n};\n/**\n * Get a list of all the Code and Coffee Chapters.\n */\nexport async function getChapters(): Promise<Chapter[]> {\n return (await (", "score": 0.8089922666549683 }, { "filename": "src/ui/calendar/coffee.dao.ts", "retrieved_chunk": "import { EventsResponse } from \"../../api\";\nimport { WebConf } from \"../web-conf\";\n/**\n * Get the details of all events from the Code and Coffee service.\n */\nexport async function getEvents(): Promise<EventsResponse> {\n const response = await fetch(`${WebConf.rootHost}/info/events`, {\n method: \"GET\",\n });\n return response.json();", "score": 0.798957109451294 }, { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": " */\nexport function getEventStats(events: EventsResponse): EventStats {\n const result: EventStats = {\n totalEvents: 0,\n totalActiveChapters: 0,\n totalRSVPs: 0,\n };\n const chapters = new Set<string>();\n events.forEach((event) => {\n result.totalEvents++;", "score": 0.7880681753158569 } ]
typescript
const response = await request({
import { forwardRef, useMemo, useCallback, useRef, useState, useEffect, Fragment, KeyboardEvent, } from 'react' import { RatingItem } from './RatingItem' import { getDynamicCssVars } from './getDynamicCssVars' import { getGroupClassNames } from './getGroupClassNames' import { getActiveClassNames } from './getActiveClassNames' import { getHFClassNames } from './getHFClassNames' import { getStaticCssVars } from './getStaticCssVars' import { getColors } from './getColors' import { getTabIndex } from './getTabIndex' import { getErrors } from './getErrors' import { getIntersectionIndex, getNumber, getRadioTestIds, getSvgTestIds, devTestId, getResetTestId, isGraphicalValueInteger, isRTLDir, useIsomorphicLayoutEffect, noop, } from './utils' import { Sizes, OrientationProps, TransitionProps, HFProps, RatingClasses } from './constants' import { defaultItemStyles } from './defaultItemStyles' import { RatingProps, Rating as RatingComponent } from './exportedTypes' import { StylesState, RequireAtLeastOne, ValidArrayColors, TabIndex, RatingItemProps, MouseEvent, FocusEvent, HTMLProps, MutableRef, } from './internalTypes' /** Thank you for using **React Rating**. * Visit https://github.com/smastrom/react-rating to read the full documentation. */ export const Rating: typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>( ( { value, items = 5, readOnly = false, onChange = noop, onHoverChange = noop, onFocus = noop, onBlur = noop, isDisabled = false, highlightOnlySelected = false, orientation = OrientationProps.HORIZONTAL, spaceBetween = Sizes.NONE, spaceInside = Sizes.SMALL, radius = Sizes.NONE, transition = TransitionProps.COLORS, itemStyles = defaultItemStyles, isRequired = false, halfFillMode = HFProps.SVG, visibleLabelId, visibleItemLabelIds, invisibleItemLabels, invisibleLabel = readOnly ? value > 0 ? `Rated ${value} on ${items}` : 'Not rated' : 'Rating Selection', resetLabel = 'Reset rating', id, className, style, }, externalRef ) => { /* Helpers */ const ratingValues = Array.from({ length: items }, (_, index) => index + 1) const hasPrecision = readOnly && !Number.isInteger(value) const isEligibleForHF = hasPrecision && !highlightOnlySelected const isNotEligibleForHF = hasPrecision && highlightOnlySelected const ratingValue = isNotEligibleForHF ? Math.round(value) : value const isDynamic = !readOnly && !isDisabled const needsDynamicCssVars = ratingValue >= 0.25 const userClassNames = typeof className === 'string' ? className : '' const absoluteHFMode = halfFillMode === HFProps.BOX ? HFProps.BOX : HFProps.SVG const deservesHF = isEligibleForHF && !isGraphicalValueInteger(ratingValue) const shouldRenderReset = !isRequired && !readOnly const tabIndexItems = isRequired ? items : items + 1 const activeStarIndex = isEligibleForHF ? getIntersectionIndex(ratingValues, ratingValue) : ratingValues.indexOf(ratingValue) /* Deps/Callbacks */ const { staticColors, arrayColors, itemShapes, absoluteStrokeWidth, absoluteBoxBorderWidth } = useMemo(() => { const { itemShapes, itemStrokeWidth, boxBorderWidth, ...colors } = itemStyles const userColors
= getColors(colors) return {
itemShapes, absoluteStrokeWidth: getNumber(itemStrokeWidth), absoluteBoxBorderWidth: getNumber(boxBorderWidth), ...userColors, } }, [itemStyles]) const hasArrayColors = Object.keys(arrayColors).length > 0 const getDynamicStyles = useCallback( (starIndex: number, shouldGetCssVars: boolean) => ({ dynamicClassNames: deservesHF ? getHFClassNames(ratingValue, items, absoluteHFMode) : getActiveClassNames(highlightOnlySelected, items, starIndex), dynamicCssVars: shouldGetCssVars && hasArrayColors ? getDynamicCssVars( arrayColors as RequireAtLeastOne<ValidArrayColors>, starIndex, highlightOnlySelected ) : [], }), [ arrayColors, hasArrayColors, highlightOnlySelected, absoluteHFMode, deservesHF, items, ratingValue, ] ) const saveTabIndex = useCallback( () => setTabIndex(getTabIndex(tabIndexItems, activeStarIndex, !isRequired)), [activeStarIndex, tabIndexItems, isRequired] ) /* Refs */ const skipStylesMount = useRef(true) const skipTabMount = useRef(true) const wrapperRef = useRef<HTMLDivElement>(null) const radioRefs = useRef<HTMLDivElement[]>([]) const isRTL = useRef(false) /* State */ const [styles, setStyles] = useState<StylesState>({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) const [tabIndex, setTabIndex] = useState<TabIndex[]>(() => { if (isDynamic) { return getTabIndex(tabIndexItems, activeStarIndex, !isRequired) } return [] }) /* Effects */ useIsomorphicLayoutEffect(() => { if (isDynamic && radioRefs.current) { isRTL.current = isRTLDir(radioRefs.current[0]) } }, [isDynamic]) useEffect(() => { if (!skipStylesMount.current) { return setStyles({ staticCssVars: getStaticCssVars(staticColors, absoluteBoxBorderWidth), ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } skipStylesMount.current = false }, [ staticColors, getDynamicStyles, absoluteBoxBorderWidth, activeStarIndex, needsDynamicCssVars, ]) useEffect(() => { if (!skipTabMount.current && isDynamic) { return saveTabIndex() } skipTabMount.current = false }, [isDynamic, saveTabIndex]) /* Log critical errors, return null */ const { shouldRender, reason } = getErrors({ items, itemShapes, }) if (!shouldRender) { console.error(reason) return null } /* Event Handlers */ function handleWhenNeeded( event: FocusEvent | MouseEvent, fromOutsideCallback: () => void, // eslint-disable-next-line @typescript-eslint/no-empty-function fromInsideCallback: () => void = () => {} ) { const fromInside = radioRefs.current.some((radio) => radio === event.relatedTarget) if (!fromInside) { fromOutsideCallback() } else { fromInsideCallback() } } function handleStarLeave() { onHoverChange(0) saveTabIndex() } function handleStarClick(event: MouseEvent, clickedIndex: number) { event.stopPropagation() if (!isRequired && activeStarIndex === clickedIndex) { onChange(0) } else { onChange(clickedIndex + 1) } } function handleMouseEnter(starIndex: number) { onHoverChange(starIndex + 1) setStyles({ ...styles, ...getDynamicStyles(starIndex, true) }) } function handleMouseLeave(event: MouseEvent) { handleWhenNeeded(event, () => { handleStarLeave() }) setStyles({ ...styles, ...getDynamicStyles(activeStarIndex, needsDynamicCssVars), }) } function handleBlur(event: FocusEvent) { handleWhenNeeded(event, () => { handleStarLeave() onBlur() }) } function handleFocus(event: FocusEvent, childIndex: number) { const isResetBtn = !isRequired && childIndex === ratingValues.length const hoveredValue = isResetBtn ? 0 : childIndex + 1 handleWhenNeeded( event, () => { onFocus() onHoverChange(hoveredValue) }, () => { onHoverChange(hoveredValue) } ) } /* Keyboard */ function handleArrowNav(siblingToFocus: number) { setTabIndex(getTabIndex(tabIndexItems, siblingToFocus, !isRequired)) radioRefs.current[siblingToFocus].focus() } function handleKeyDown(event: KeyboardEvent<HTMLDivElement>, childIndex: number) { let siblingToFocus = 0 const lastSibling = isRequired ? ratingValues.length - 1 : ratingValues.length const prevSibling = childIndex - 1 const nextSibling = childIndex + 1 const isResetBtn = !isRequired && childIndex === ratingValues.length const isFiringFromLast = lastSibling === childIndex const isFiringFromFirst = childIndex === 0 const prevToFocus = isFiringFromFirst ? lastSibling : prevSibling const nextToFocus = isFiringFromLast ? 0 : nextSibling switch (event.code) { case 'Shift': case 'Tab': return true case 'ArrowDown': case 'ArrowRight': siblingToFocus = !isRTL.current ? nextToFocus : prevToFocus return handleArrowNav(siblingToFocus) case 'ArrowUp': case 'ArrowLeft': siblingToFocus = !isRTL.current ? prevToFocus : nextToFocus return handleArrowNav(siblingToFocus) case 'Enter': case 'Space': event.preventDefault() return onChange(isResetBtn ? 0 : childIndex + 1) } event.preventDefault() event.stopPropagation() } /* Group props */ const groupClassNames = getGroupClassNames({ className: userClassNames, radius, readOnly, isDisabled, isDynamic, transition, orientation, absoluteBoxBorderWidth, absoluteStrokeWidth, spaceBetween, spaceInside, }) function getAriaGroupProps() { if (!readOnly) { const isAriaRequired = isRequired && !isDisabled const ariaProps: HTMLProps = { role: 'radiogroup', 'aria-required': isAriaRequired, } if (isAriaRequired) { ariaProps['aria-invalid'] = ratingValue <= 0 } if (typeof visibleLabelId === 'string' && visibleLabelId.length > 0) { ariaProps['aria-labelledby'] = visibleLabelId } else { ariaProps['aria-label'] = invisibleLabel } return ariaProps } return { role: 'img', 'aria-label': invisibleLabel, } } function pushGroupRefs(element: HTMLDivElement) { if (isDynamic && !isRequired) { ;(wrapperRef as MutableRef).current = element } if (externalRef) { ;(externalRef as MutableRef).current = element } } /* Radio props */ function getRefs(childIndex: number) { return { ref: (childNode: HTMLDivElement) => (radioRefs.current[childIndex] = childNode), } } function getKeyboardProps(childIndex: number): HTMLProps { return { tabIndex: tabIndex[childIndex], onKeyDown: (event) => handleKeyDown(event, childIndex), } } function getMouseProps(starIndex: number): HTMLProps { return { onClick: (event) => handleStarClick(event, starIndex), onMouseEnter: () => handleMouseEnter(starIndex), onMouseLeave: handleMouseLeave, } } function getAriaRadioProps(starIndex: number): HTMLProps { if (readOnly) { return {} } const labelProps: HTMLProps = {} if (Array.isArray(visibleItemLabelIds)) { labelProps['aria-labelledby'] = visibleItemLabelIds[starIndex] } else { const radioLabels = Array.isArray(invisibleItemLabels) ? invisibleItemLabels : ratingValues.map((_, index: number) => `Rate ${index + 1}`) labelProps['aria-label'] = radioLabels[starIndex] } if (isDisabled) { labelProps['aria-disabled'] = 'true' } return { role: 'radio', 'aria-checked': starIndex + 1 === ratingValue, ...labelProps, } } function getInteractiveRadioProps(starIndex: number): HTMLProps { if (!isDynamic) { return {} } return { ...getRefs(starIndex), ...getKeyboardProps(starIndex), ...getMouseProps(starIndex), onFocus: (event) => handleFocus(event, starIndex), onBlur: (event) => handleBlur(event), } } function getResetProps(childIndex: number): HTMLProps { return { className: RatingClasses.RESET, role: 'radio', 'aria-label': resetLabel, 'aria-checked': ratingValue === 0, onClick: () => onChange(0), onFocus: (event) => { handleFocus(event, childIndex) wrapperRef.current?.classList.add(RatingClasses.GROUP_RESET) }, onBlur: (event) => { handleBlur(event) wrapperRef.current?.classList.remove(RatingClasses.GROUP_RESET) }, ...getResetTestId(), ...getKeyboardProps(childIndex), ...getRefs(childIndex), ...(isDisabled ? { 'aria-disabled': 'true' } : {}), } } /* SVG props */ function getRatingItemProps(starIndex: number): RatingItemProps { const sharedProps = { itemShapes: Array.isArray(itemShapes) ? itemShapes[starIndex] : itemShapes, itemStrokeWidth: absoluteStrokeWidth, orientation, hasHF: false, testId: getSvgTestIds(starIndex), } if (deservesHF && absoluteHFMode === HFProps.SVG) { sharedProps.hasHF = starIndex === activeStarIndex } return sharedProps } /* Render */ return ( <div id={id} className={groupClassNames} style={{ ...style, ...styles.staticCssVars }} ref={pushGroupRefs} {...getAriaGroupProps()} {...devTestId} > {ratingValues.map((value, index) => ( <Fragment key={value}> <div className={`${RatingClasses.BOX} ${styles.dynamicClassNames[index]}`} style={styles.dynamicCssVars[index]} {...getAriaRadioProps(index)} {...getInteractiveRadioProps(index)} {...getRadioTestIds(index)} > <RatingItem {...getRatingItemProps(index)} /> </div> {shouldRenderReset && index === ratingValues.length - 1 && ( <div {...getResetProps(index + 1)} /> )} </Fragment> ))} </div> ) } ) Rating.displayName = 'Rating'
src/Rating.tsx
SkyCaptainess-React-rating-components-625733e
[ { "filename": "src/RatingItem.tsx", "retrieved_chunk": "import { RatingItemProps, SvgData } from './internalTypes'\nexport function RatingItem({\n itemShapes,\n testId,\n itemStrokeWidth = 0,\n orientation = OrientationProps.HORIZONTAL,\n hasHF = false,\n}: RatingItemProps) {\n const strokeOffset = itemStrokeWidth > 0 ? -(itemStrokeWidth / 2) : 0\n const translateOffset = itemStrokeWidth > 0 ? `${strokeOffset} ${strokeOffset}` : '0 0'", "score": 0.861843466758728 }, { "filename": "src/getStaticCssVars.ts", "retrieved_chunk": " if (isPositiveNum(boxBorderWidth)) {\n cssVars[ItemVars.BORDER_WIDTH] = `${boxBorderWidth}px`\n }\n const colorsEntries = Object.entries(staticColors)\n if (colorsEntries.length > 0) {\n for (const [key, value] of colorsEntries) {\n setColorCssVars(cssVars, key, value)\n }\n }\n return cssVars", "score": 0.860662579536438 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": " /** Inactive stroke color of the SVG. */\n inactiveStrokeColor?: string\n /** Inactive background color of the SVG bounding box. */\n inactiveBoxColor?: string\n /** Inactive border color of the SVG bounding box. */\n inactiveBoxBorderColor?: string\n}\nexport type Colors = MaybeArrayColors & NonArrayColors\n/** Custom shapes and colors, visit https://github.com/smastrom/react-rating for more info. */\nexport type ItemStyles = Colors & {", "score": 0.8380016088485718 }, { "filename": "src/RatingItem.tsx", "retrieved_chunk": " }\n return {}\n }\n function getStrokeAttribute() {\n if (itemStrokeWidth > 0) {\n return {\n strokeWidth: itemStrokeWidth,\n }\n }\n return {}", "score": 0.8296146988868713 }, { "filename": "src/exportedTypes.ts", "retrieved_chunk": "import {\n CSSProperties,\n ForwardRefExoticComponent,\n RefAttributes,\n Dispatch,\n SetStateAction,\n} from 'react'\nexport type MaybeArrayColors = {\n /** Active fill color of the SVG, it can be an array of colors in ascending order. */\n activeFillColor?: string | string[]", "score": 0.8282839059829712 } ]
typescript
= getColors(colors) return {
import React, { ReactNode, useEffect, useState } from "react"; import styled from "styled-components"; import { People24Filled } from "@fluentui/react-icons"; import { Share24Filled } from "@fluentui/react-icons"; import { MeetupEvent } from "../../api/dao/meetup.dao"; import { WebConf } from "../web-conf"; const PeopleIcon = People24Filled; const ShareIcon = Share24Filled; const EventContainer = styled.div` @import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap"); font-family: "Source Sans Pro", sans-serif; display: flex; justify-content: space-between; flex-direction: row; gap: 15px; border-bottom: 1px solid #dcdcdc; padding-bottom: 15px; padding-top: 15px; width: 100%; @media (max-width: 600px) { flex-direction: column; gap: 10px; } `; const BreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { justify-content: left; } `; const DateContainer = styled.div` padding-top: 10px; display: flex; flex-direction: column; align-items: center; `; const DateNumber = styled.p` margin: 0; font-size: 24px; font-weight: 700; `; const DateMonth = styled.p` margin: 0; font-size: 15px; font-weight: 400; color: #6c6c6c; `; const IconContainer = styled.div` display: flex; flex-direction: column; width: 60px; `; const IconBreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { display: none; } `; const CityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; `; const SmallCityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; width: 30px; height: 30px; display: none; @media (max-width: 600px) { display: block; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; max-width: 400px; gap: 10px; @media (max-width: 600px) { align-items: center; } `; const DateInfo = styled.div` display: flex; flex-direction: row; font-weight: 400; color: #6c6c6c; font-size: 16px; margin: 0; align-items: end; gap: 10px; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const EventInfo = styled.p` font-weight: 700; font-size: 24px; margin: 0; @media (max-width: 600px) { font-size: 20px; text-align: center; } `; const DescriptionInfo = styled.p` color: #6c6c6c; font-weight: 400; margin: 0; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const RsvpContainer = styled.div` display: flex; flex-direction: column; align-items: end; @media (max-width: 600px) { flex-direction: row; justify-content: space-between; } `; const RsvpBreakContainer = styled.div` display: flex; flex-direction: column; `; const CityContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; width: 100%; `; const CityLabel = styled.p` font-weight: 400; margin: 0; font-size: 12px; color: #6c6c6c; `; const AttendeeContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; `; const AttendeeCount = styled.p` font-weight: 700; margin: 0 0 0 5px; font-size: 15px; `; const AttendeeLabel = styled.p` font-weight: 400; margin: 0; font-size: 15px; color: #6c6c6c; padding-left: 4px; `; const EventImage = styled.img` max-width: 111px; max-height: 74px; border-radius: 5px; `; const CoffeeButton = styled.button` display: flex; flex-direction: row; align-items: center; justify-content: center; background: #d4b9ff; gap: 10px; border: 1px solid #000000; border-radius: 5px; font-weight: 700; font-size: 15px; padding: 8px 16px; transition: background 0.2s, box-shadow 0.2s; :hover { background: #dbc4ff; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12); cursor: pointer; } :active { background: #a063ff; box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); } `; const MonthShortFormatter = new Intl.DateTimeFormat("default", { month: "short", }); const MonthLongFormatter = new Intl.DateTimeFormat("default", { month: "long", }); const WeekdayFormatter = new Intl.DateTimeFormat("default", { weekday: "long", }); const DayFormatter = new Intl.DateTimeFormat("default", { day: "numeric" }); const HourFormatter = new Intl.DateTimeFormat("default", { hour: "numeric", hour12: true, minute: "2-digit", }); const EVENT_DESCRIPTION_LENGTH = 125;
export function CoffeeEvent({ event }: { event: MeetupEvent }) {
const [iconImage, setIconImage] = useState( undefined as undefined | ReactNode ); const [smallIconImage, setSmallIconImage] = useState( undefined as undefined | ReactNode ); function rsvpAction() { window.open(event.eventUrl, "_blank"); } useEffect(() => { fetch( `${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => { if (response.ok) { setIconImage( <CityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); setSmallIconImage( <SmallCityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); } }); }, []); const date = new Date(event.dateTime); const eventDateString = `${WeekdayFormatter.format( date )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format( date )} at ${HourFormatter.format(date)}`; const descriptionString = event.description.length > EVENT_DESCRIPTION_LENGTH ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + " ..." : event.description; return ( <EventContainer> <BreakContainer> <IconBreakContainer> <DateContainer> <DateNumber>{DayFormatter.format(date)}</DateNumber> <DateMonth>{MonthShortFormatter.format(date)}</DateMonth> </DateContainer> <IconContainer>{iconImage}</IconContainer> </IconBreakContainer> <InfoContainer> <DateInfo> {smallIconImage} {eventDateString} </DateInfo> <EventInfo>{event.title}</EventInfo> <DescriptionInfo>{descriptionString}</DescriptionInfo> </InfoContainer> </BreakContainer> <RsvpContainer> <EventImage src={event.imageUrl} alt="rsvp" /> <RsvpBreakContainer> <CityContainer> <CityLabel> {event.venue?.city || event.group.city},{" "} {event.venue?.state.toUpperCase() || event.group.state.toUpperCase()} </CityLabel> </CityContainer> <AttendeeContainer> <PeopleIcon /> <AttendeeCount>{event.going}</AttendeeCount> <AttendeeLabel>attendees</AttendeeLabel> </AttendeeContainer> <CoffeeButton onClick={rsvpAction}> RSVP <ShareIcon /> </CoffeeButton> </RsvpBreakContainer> </RsvpContainer> </EventContainer> ); }
src/ui/calendar/coffee-event.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-calendar.tsx", "retrieved_chunk": " border: 2px solid black;\n border-radius: 2px;\n }\n`;\nexport function CoffeeCalendar({ height }: { height: number }) {\n const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>);\n const [showStats, setShowStats] = useState(false as boolean);\n const [stats, setStats] = useState(undefined as undefined | EventStats);\n useEffect(() => {\n getEvents().then((events) => {", "score": 0.6963253021240234 }, { "filename": "src/ui/calendar/coffee-calendar.tsx", "retrieved_chunk": "import React, { useEffect, useState } from \"react\";\nimport { CoffeeEvent } from \"./coffee-event\";\nimport styled from \"styled-components\";\nimport { getEvents } from \"./coffee.dao\";\nimport { EventStats, getEventStats } from \"./events.util\";\nimport { CoffeeEventStats } from \"./coffee-event-stats\";\nconst CalendarContainer = styled.div`\n display: flex;\n flex-direction: column;\n height: ${({ height }: { height: number }) => height}px;", "score": 0.685116708278656 }, { "filename": "src/api/dao/email.dao.ts", "retrieved_chunk": "import { request } from \"../util/request.util\";\nimport { AppConf } from \"../app-conf\";\nexport type EmailContent = {\n recipient: string | Array<string>;\n subject: string;\n body: string;\n};\nexport async function sendEmail(email: EmailContent) {\n await request({\n name: \"Send Email\",", "score": 0.6770378947257996 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": "import { request } from \"../util/request.util\";\nimport { AppConf } from \"../app-conf\";\n/**\n * The info for a Code and Coffee Chapter.\n */\nexport type Chapter = {\n name: string;\n meetupGroupUrlName: string;\n};\nexport type NotificationSetting = {", "score": 0.6589370965957642 }, { "filename": "src/ui/index.tsx", "retrieved_chunk": "import { registerReactWebComponent } from \"./wc.util\";\nimport { CoffeeCalendar } from \"./calendar/coffee-calendar\";\n// import {CoffeeSwagger} from \"./swagger/swagger\";\nregisterReactWebComponent({\n name: \"coffee-calendar\",\n attributes: [\"height\"],\n Component: CoffeeCalendar,\n});\n// TODO Fix Swagger\n// registerReactWebComponent({", "score": 0.6567385196685791 } ]
typescript
export function CoffeeEvent({ event }: { event: MeetupEvent }) {
import { APIGatewayProxyEventV2 } from "aws-lambda"; import { APIGatewayProxyStructuredResultV2 } from "aws-lambda/trigger/api-gateway-proxy"; import { MeetupEvent } from "./dao/meetup.dao"; import { AppConf } from "./app-conf"; import { Controller, routes } from "./routes"; import colors from "colors"; export type EventsResponse = Array<MeetupEvent>; export async function handler( event: APIGatewayProxyEventV2 ): Promise<APIGatewayProxyStructuredResultV2> { try { return await handleRequest(event); } catch (e) { console.error(`Internal server error: ${e}`); return { statusCode: 500, body: JSON.stringify({ message: "Internal server error", requestId: event.requestContext.requestId, }), headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, }; } } async function handleRequest( event: APIGatewayProxyEventV2 ): Promise<APIGatewayProxyStructuredResultV2> { console.log("request received"); if (!isApiKeyValid(event)) { return { statusCode: 401, body: JSON.stringify({ message: "Unauthorized", }), headers: { "Content-Type": "application/json", }, }; } const path = event.requestContext.http.path; const method = event.requestContext.http.method.toUpperCase(); let controller = undefined as undefined | Controller; for (const route of routes) { if (method === route.method && new RegExp(`^${route.path}$`).test(path)) { controller = route.controller; break; } } if (controller) {
const response = await controller(event);
if (!response.headers) { response.headers = {}; } response.headers["Access-Control-Allow-Origin"] = "*"; return response; } console.log( colors.blue("No controller found for path ") + colors.yellow(`"${path}"`) ); return { statusCode: 404, body: JSON.stringify({ message: "Not found", requestId: event.requestContext.requestId, }), headers: { "Content-Type": "application/json", }, }; } const API_KEY_PATH = /^\/api\/.*/; /** * Checks if an API key is needed, and if so, if it is valid. API Keys are required for all non cached requests. * @param request The request to validate. */ function isApiKeyValid(request: APIGatewayProxyEventV2): boolean { if (API_KEY_PATH.test(request.requestContext.http.path)) { return request.headers?.["x-api-key"] === AppConf.apiKey; } return true; }
src/api/index.ts
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/service/notify.service.ts", "retrieved_chunk": " throw new Error(\"INVALID_NOTIFICATION\");\n }\n const channelSetting = (await getNotificationSettings()).find(\n (setting) => setting.name === notification.channel\n );\n if (!channelSetting) {\n throw new Error(\"INVALID_NOTIFICATION\");\n }\n if (channelSetting.email) {\n await sendEmail({", "score": 0.7506107091903687 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": " })\n ) +\n \"\\n\"\n );\n let response;\n try {\n response = await fetch(options.url, {\n method: options.method,\n headers: options.headers,\n body: JSON.stringify(options.body),", "score": 0.7415903806686401 }, { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": "}\nconst chapterRegex = /(?<=\\/info\\/chapter-icons\\/).*$/;\nfunction extractChapter(path: string): string {\n const results = path.match(chapterRegex);\n if (results === null) {\n throw new Error(`Could not extract chapter from path ${path}`);\n }\n return results[0];\n}", "score": 0.7360594868659973 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " * @param response The response from the query.\n */\nfunction processResponse(response: QueryResponse): Array<MeetupEvent> {\n const result = [] as Array<MeetupEvent>;\n for (const group of Object.values(response.data)) {\n if (group) {\n for (const event of group.upcomingEvents.edges) {\n result.push(event.node);\n }\n }", "score": 0.7305944561958313 }, { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": " await getChapterIcon(extractChapter(event.rawPath))\n ).toString(\"base64\"),\n headers: {\n \"Content-Type\": \"image/png\",\n },\n isBase64Encoded: true,\n };\n } catch (e: any | Response) {\n if (e.status === 404) {\n return {", "score": 0.7268697023391724 } ]
typescript
const response = await controller(event);
import React, { useEffect, useState } from "react"; import { CoffeeEvent } from "./coffee-event"; import styled from "styled-components"; import { getEvents } from "./coffee.dao"; import { EventStats, getEventStats } from "./events.util"; import { CoffeeEventStats } from "./coffee-event-stats"; const CalendarContainer = styled.div` display: flex; flex-direction: column; height: ${({ height }: { height: number }) => height}px; padding: 15px; border-radius: 20px; box-shadow: 3px 3px 33px rgba(0, 0, 0, 0.04); @media (max-width: 600px) { padding: 0; } `; const EventTitle = styled.h1` @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap"); font-family: "Cormorant Garamond", serif; font-weight: 700; font-size: 36px; margin: 0 0 10px 0; `; const EventHolder = styled.div` border-top: 1px solid #dcdcdc; border-bottom: 1px solid #dcdcdc; overflow-y: scroll; padding-right: 20px; display: flex; flex-direction: column; align-items: center; /* width */ ::-webkit-scrollbar { width: 10px; transform: rotate(180deg); } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d4b9ff; border: 1px solid black; border-radius: 2px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #dbc4ff; border: 2px solid black; border-radius: 2px; } `; export function CoffeeCalendar({ height }: { height: number }) { const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>); const [showStats, setShowStats] = useState(false as boolean); const [stats, setStats] = useState(undefined as undefined | EventStats); useEffect(() => { getEvents().then((events) => { const newCoffeeEvents = [] as Array<JSX.Element>; for (const event of events) { if (event) { newCoffeeEvents.push(<CoffeeEvent event={event} key={event.id} />); } } setCoffeeEvents(newCoffeeEvents); setStats(getEventStats(events)); }); }, []); useEffect(() => { function displayDialogListener(event: KeyboardEvent): void { if (event.code === "KeyI" && event.ctrlKey) { setShowStats(!showStats); } } document.addEventListener("keydown", displayDialogListener); return () => { document.removeEventListener("keydown", displayDialogListener); }; }, [showStats]); return ( <CalendarContainer height={height}> <EventTitle>Events</EventTitle>
{showStats && stats && <CoffeeEventStats stats={stats} />}
<EventHolder>{coffeeEvents}</EventHolder> </CalendarContainer> ); }
src/ui/calendar/coffee-calendar.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-event-stats.tsx", "retrieved_chunk": "`;\nexport function CoffeeEventStats({ stats }: { stats: EventStats }) {\n return (\n <StatsContainer>\n <Stat>Events: {stats.totalEvents}</Stat>\n <Stat>RSVPS: {stats.totalRSVPs}</Stat>\n <Stat>Active Chapters: {stats.totalActiveChapters}</Stat>\n </StatsContainer>\n );\n}", "score": 0.7810767292976379 }, { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": "const EVENT_DESCRIPTION_LENGTH = 125;\nexport function CoffeeEvent({ event }: { event: MeetupEvent }) {\n const [iconImage, setIconImage] = useState(\n undefined as undefined | ReactNode\n );\n const [smallIconImage, setSmallIconImage] = useState(\n undefined as undefined | ReactNode\n );\n function rsvpAction() {\n window.open(event.eventUrl, \"_blank\");", "score": 0.7755153179168701 }, { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": " )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format(\n date\n )} at ${HourFormatter.format(date)}`;\n const descriptionString =\n event.description.length > EVENT_DESCRIPTION_LENGTH\n ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + \" ...\"\n : event.description;\n return (\n <EventContainer>\n <BreakContainer>", "score": 0.7402757406234741 }, { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": " }\n useEffect(() => {\n fetch(\n `${\n WebConf.rootHost\n }/info/chapter-icons/${event.group.urlname.toLowerCase()}`\n ).then((response) => {\n if (response.ok) {\n setIconImage(\n <CityIcon", "score": 0.7048719525337219 }, { "filename": "src/ui/wc.util.tsx", "retrieved_chunk": " connectedCallback() {\n const attrs = attributes.reduce(\n (acc, key) =>\n Object.assign(acc, {\n [key]: this.getAttribute(key) ?? undefined,\n }),\n {}\n );\n this.root.render(\n <StyleSheetManager target={this.shadow}>", "score": 0.6986750960350037 } ]
typescript
{showStats && stats && <CoffeeEventStats stats={stats} />}
import React, { ReactNode, useEffect, useState } from "react"; import styled from "styled-components"; import { People24Filled } from "@fluentui/react-icons"; import { Share24Filled } from "@fluentui/react-icons"; import { MeetupEvent } from "../../api/dao/meetup.dao"; import { WebConf } from "../web-conf"; const PeopleIcon = People24Filled; const ShareIcon = Share24Filled; const EventContainer = styled.div` @import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap"); font-family: "Source Sans Pro", sans-serif; display: flex; justify-content: space-between; flex-direction: row; gap: 15px; border-bottom: 1px solid #dcdcdc; padding-bottom: 15px; padding-top: 15px; width: 100%; @media (max-width: 600px) { flex-direction: column; gap: 10px; } `; const BreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { justify-content: left; } `; const DateContainer = styled.div` padding-top: 10px; display: flex; flex-direction: column; align-items: center; `; const DateNumber = styled.p` margin: 0; font-size: 24px; font-weight: 700; `; const DateMonth = styled.p` margin: 0; font-size: 15px; font-weight: 400; color: #6c6c6c; `; const IconContainer = styled.div` display: flex; flex-direction: column; width: 60px; `; const IconBreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { display: none; } `; const CityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; `; const SmallCityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; width: 30px; height: 30px; display: none; @media (max-width: 600px) { display: block; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; max-width: 400px; gap: 10px; @media (max-width: 600px) { align-items: center; } `; const DateInfo = styled.div` display: flex; flex-direction: row; font-weight: 400; color: #6c6c6c; font-size: 16px; margin: 0; align-items: end; gap: 10px; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const EventInfo = styled.p` font-weight: 700; font-size: 24px; margin: 0; @media (max-width: 600px) { font-size: 20px; text-align: center; } `; const DescriptionInfo = styled.p` color: #6c6c6c; font-weight: 400; margin: 0; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const RsvpContainer = styled.div` display: flex; flex-direction: column; align-items: end; @media (max-width: 600px) { flex-direction: row; justify-content: space-between; } `; const RsvpBreakContainer = styled.div` display: flex; flex-direction: column; `; const CityContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; width: 100%; `; const CityLabel = styled.p` font-weight: 400; margin: 0; font-size: 12px; color: #6c6c6c; `; const AttendeeContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; `; const AttendeeCount = styled.p` font-weight: 700; margin: 0 0 0 5px; font-size: 15px; `; const AttendeeLabel = styled.p` font-weight: 400; margin: 0; font-size: 15px; color: #6c6c6c; padding-left: 4px; `; const EventImage = styled.img` max-width: 111px; max-height: 74px; border-radius: 5px; `; const CoffeeButton = styled.button` display: flex; flex-direction: row; align-items: center; justify-content: center; background: #d4b9ff; gap: 10px; border: 1px solid #000000; border-radius: 5px; font-weight: 700; font-size: 15px; padding: 8px 16px; transition: background 0.2s, box-shadow 0.2s; :hover { background: #dbc4ff; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12); cursor: pointer; } :active { background: #a063ff; box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); } `; const MonthShortFormatter = new Intl.DateTimeFormat("default", { month: "short", }); const MonthLongFormatter = new Intl.DateTimeFormat("default", { month: "long", }); const WeekdayFormatter = new Intl.DateTimeFormat("default", { weekday: "long", }); const DayFormatter = new Intl.DateTimeFormat("default", { day: "numeric" }); const HourFormatter = new Intl.DateTimeFormat("default", { hour: "numeric", hour12: true, minute: "2-digit", }); const EVENT_DESCRIPTION_LENGTH = 125; export function CoffeeEvent({ event }: { event: MeetupEvent }) { const [iconImage, setIconImage] = useState( undefined as undefined | ReactNode ); const [smallIconImage, setSmallIconImage] = useState( undefined as undefined | ReactNode ); function rsvpAction() { window.open(event.eventUrl, "_blank"); } useEffect(() => { fetch( `${ WebConf.rootHost
}/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => {
if (response.ok) { setIconImage( <CityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); setSmallIconImage( <SmallCityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); } }); }, []); const date = new Date(event.dateTime); const eventDateString = `${WeekdayFormatter.format( date )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format( date )} at ${HourFormatter.format(date)}`; const descriptionString = event.description.length > EVENT_DESCRIPTION_LENGTH ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + " ..." : event.description; return ( <EventContainer> <BreakContainer> <IconBreakContainer> <DateContainer> <DateNumber>{DayFormatter.format(date)}</DateNumber> <DateMonth>{MonthShortFormatter.format(date)}</DateMonth> </DateContainer> <IconContainer>{iconImage}</IconContainer> </IconBreakContainer> <InfoContainer> <DateInfo> {smallIconImage} {eventDateString} </DateInfo> <EventInfo>{event.title}</EventInfo> <DescriptionInfo>{descriptionString}</DescriptionInfo> </InfoContainer> </BreakContainer> <RsvpContainer> <EventImage src={event.imageUrl} alt="rsvp" /> <RsvpBreakContainer> <CityContainer> <CityLabel> {event.venue?.city || event.group.city},{" "} {event.venue?.state.toUpperCase() || event.group.state.toUpperCase()} </CityLabel> </CityContainer> <AttendeeContainer> <PeopleIcon /> <AttendeeCount>{event.going}</AttendeeCount> <AttendeeLabel>attendees</AttendeeLabel> </AttendeeContainer> <CoffeeButton onClick={rsvpAction}> RSVP <ShareIcon /> </CoffeeButton> </RsvpBreakContainer> </RsvpContainer> </EventContainer> ); }
src/ui/calendar/coffee-event.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": " * @param chapter The chapter to get the icon for.\n */\nexport async function getChapterIcon(chapter: string): Promise<ArrayBuffer> {\n return await (\n await request({\n name: \"Chapter Icon\",\n url: `${AppConf.settingsBaseUrl}/chapter-icons/${chapter}.png`,\n method: \"GET\",\n })\n ).arrayBuffer();", "score": 0.6934859752655029 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " const finalQuery = formQuery(chapters);\n const response = await request({\n name: \"Meetup Event\",\n url: `${AppConf.meetupApiBaseUrl}/gql`,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: { query: finalQuery },\n });\n return processResponse((await response.json()) as QueryResponse);\n}", "score": 0.671964168548584 }, { "filename": "src/api/dao/github.dao.ts", "retrieved_chunk": " repo: string,\n issue: GithubIssue\n): Promise<GithubIssueResponse> {\n return (\n await request({\n name: \"Create Github Issue\",\n url: `${AppConf.githubApiBaseUrl}/repos/${repo}/issues`,\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",", "score": 0.6529728770256042 }, { "filename": "src/ui/calendar/coffee-calendar.tsx", "retrieved_chunk": " useEffect(() => {\n function displayDialogListener(event: KeyboardEvent): void {\n if (event.code === \"KeyI\" && event.ctrlKey) {\n setShowStats(!showStats);\n }\n }\n document.addEventListener(\"keydown\", displayDialogListener);\n return () => {\n document.removeEventListener(\"keydown\", displayDialogListener);\n };", "score": 0.643166184425354 }, { "filename": "src/api/service/notify.service.ts", "retrieved_chunk": " body: notification.message,\n recipient: channelSetting.email,\n subject: channelSetting.emailTitlePrepend\n ? `${channelSetting.emailTitlePrepend}${notification.title}`\n : notification.title,\n });\n }\n if (channelSetting.github) {\n await createIssue(channelSetting.github, {\n title: notification.title,", "score": 0.6379600167274475 } ]
typescript
}/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => {
import type { AbstractComponent, Component, Mixed } from "./component"; /** * `Provider<N, T, D>` represents a component provider. * @param N The name of the component. * @param T The type of the provided instance. * @param D The type of the dependencies. */ export type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{ // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider"; name: N; factory: Factory<T, D>; }>; export type Factory<T extends unknown, D extends unknown> = | FactoryFunction<T, D> | FactoryClass<T, D>; export type FactoryFunction<T extends unknown, D extends unknown> = (deps: D) => T; export type FactoryClass<T extends unknown, D extends unknown> = new (deps: D) => T; export function invokecFactory<T extends unknown, D extends unknown>( factory: Factory<T, D>, deps: D ): T { // check if the factory is a class (not a perfect check though) const desc = Object.getOwnPropertyDescriptor(factory, "prototype"); if (desc && !desc.writable) { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return new (factory as FactoryClass<T, D>)(deps); } else { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return (factory as FactoryFunction<T, D>)(deps); } } /** * The upper bound of provider types. */ export type AbstractProvider = Provider<string, unknown, never>; export type ProviderName<P extends AbstractProvider> = P extends Provider<infer N, unknown, never> ? N : never; export type ProviderDependencies<P extends AbstractProvider> = ( P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never ) extends (deps: infer I) => unknown ? I : never; export type ReconstructComponent<P extends AbstractProvider> = P extends Provider< infer N, infer T, never > ? Component<N, T> : never; export type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{ [K in keyof Ps]: ReconstructComponent<Ps[K]>; }>; /** * Returns the provider type that implements a component. * @param C A component. * @param Ds A list of dependencies. */ export type Impl< C extends AbstractComponent, Ds extends AbstractComponent[] = [], > = C extends Component
<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;
export type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs< Impl<C, Ds> >; type _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D> ? [name: N, factory: Factory<T, D>] : never; /** * Creates an implementation of a component. * @param name The name of the component. * @param factory A factory function or class that creates an instance of the component. * @returns An implementation (provider) of the component. */ export function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>( ...[name, factory]: ImplArgs<C, Ds> ): Impl<C, Ds> { const provider: AbstractProvider = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider", name, factory, }; // ImplArgs<C, Ds> and Impl<C, Ds> always have the same shape, so it's safe to cast. // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return provider as Impl<C, Ds>; }
src/provider.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.ts", "retrieved_chunk": " type: T;\n};\n/**\n * The upper bound of component types.\n */\nexport type AbstractComponent = Component<string, unknown>;\n/**\n * Returns the instance type of a component.\n * @param C A component.\n */", "score": 0.8741025328636169 }, { "filename": "src/mixer.ts", "retrieved_chunk": " * @param Ps A list of providers to be mixed.\n */\nexport type Mixer<Ps extends AbstractProvider[]> = Readonly<{\n /**\n * Extends the mixer with more providers.\n * @params providers Additional providers to be mixed.\n * @returns An extended mixer object.\n */\n with: MixerMethodWith<Ps>;\n /**", "score": 0.8552104234695435 }, { "filename": "src/component.ts", "retrieved_chunk": "export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T>\n ? _Instance<N, T>\n : never;\ntype _Instance<N extends string, T extends unknown> = N extends unknown\n ? IsFiniteString<N> extends true\n ? { readonly [N0 in N]: T }\n : { readonly [N0 in N]?: T }\n : never;\n/**\n * Returns the mixed instance type of components.", "score": 0.8470720648765564 }, { "filename": "src/mixer.ts", "retrieved_chunk": " dependencies: MissingDependencies<P, Ps>;\n };\n };\ntype MissingDependencies<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = _MissingDependencies<ProviderDependencies<P>, MixedProvidedInstance<Ps>>;\ntype _MissingDependencies<D extends unknown, I extends unknown> = D extends unknown\n ? Wrap<\n {", "score": 0.8374638557434082 }, { "filename": "src/component.ts", "retrieved_chunk": " ...infer Xs extends AbstractComponent[],\n infer X extends AbstractComponent,\n ] ? _FilteredInstances<Xs, Is, Instance<X>, K>\n : [];\n// prettier-ignore\ntype _FilteredInstances<\n Cs extends AbstractComponent[],\n Is extends Array<{}>,\n I extends {},\n K extends string", "score": 0.8286213278770447 } ]
typescript
<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;
import React, { ReactNode, useEffect, useState } from "react"; import styled from "styled-components"; import { People24Filled } from "@fluentui/react-icons"; import { Share24Filled } from "@fluentui/react-icons"; import { MeetupEvent } from "../../api/dao/meetup.dao"; import { WebConf } from "../web-conf"; const PeopleIcon = People24Filled; const ShareIcon = Share24Filled; const EventContainer = styled.div` @import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap"); font-family: "Source Sans Pro", sans-serif; display: flex; justify-content: space-between; flex-direction: row; gap: 15px; border-bottom: 1px solid #dcdcdc; padding-bottom: 15px; padding-top: 15px; width: 100%; @media (max-width: 600px) { flex-direction: column; gap: 10px; } `; const BreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { justify-content: left; } `; const DateContainer = styled.div` padding-top: 10px; display: flex; flex-direction: column; align-items: center; `; const DateNumber = styled.p` margin: 0; font-size: 24px; font-weight: 700; `; const DateMonth = styled.p` margin: 0; font-size: 15px; font-weight: 400; color: #6c6c6c; `; const IconContainer = styled.div` display: flex; flex-direction: column; width: 60px; `; const IconBreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { display: none; } `; const CityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; `; const SmallCityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; width: 30px; height: 30px; display: none; @media (max-width: 600px) { display: block; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; max-width: 400px; gap: 10px; @media (max-width: 600px) { align-items: center; } `; const DateInfo = styled.div` display: flex; flex-direction: row; font-weight: 400; color: #6c6c6c; font-size: 16px; margin: 0; align-items: end; gap: 10px; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const EventInfo = styled.p` font-weight: 700; font-size: 24px; margin: 0; @media (max-width: 600px) { font-size: 20px; text-align: center; } `; const DescriptionInfo = styled.p` color: #6c6c6c; font-weight: 400; margin: 0; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const RsvpContainer = styled.div` display: flex; flex-direction: column; align-items: end; @media (max-width: 600px) { flex-direction: row; justify-content: space-between; } `; const RsvpBreakContainer = styled.div` display: flex; flex-direction: column; `; const CityContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; width: 100%; `; const CityLabel = styled.p` font-weight: 400; margin: 0; font-size: 12px; color: #6c6c6c; `; const AttendeeContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; `; const AttendeeCount = styled.p` font-weight: 700; margin: 0 0 0 5px; font-size: 15px; `; const AttendeeLabel = styled.p` font-weight: 400; margin: 0; font-size: 15px; color: #6c6c6c; padding-left: 4px; `; const EventImage = styled.img` max-width: 111px; max-height: 74px; border-radius: 5px; `; const CoffeeButton = styled.button` display: flex; flex-direction: row; align-items: center; justify-content: center; background: #d4b9ff; gap: 10px; border: 1px solid #000000; border-radius: 5px; font-weight: 700; font-size: 15px; padding: 8px 16px; transition: background 0.2s, box-shadow 0.2s; :hover { background: #dbc4ff; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12); cursor: pointer; } :active { background: #a063ff; box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); } `; const MonthShortFormatter = new Intl.DateTimeFormat("default", { month: "short", }); const MonthLongFormatter = new Intl.DateTimeFormat("default", { month: "long", }); const WeekdayFormatter = new Intl.DateTimeFormat("default", { weekday: "long", }); const DayFormatter = new Intl.DateTimeFormat("default", { day: "numeric" }); const HourFormatter = new Intl.DateTimeFormat("default", { hour: "numeric", hour12: true, minute: "2-digit", }); const EVENT_DESCRIPTION_LENGTH = 125; export function CoffeeEvent({ event }: { event: MeetupEvent }) { const [iconImage, setIconImage] = useState( undefined as undefined | ReactNode ); const [smallIconImage, setSmallIconImage] = useState( undefined as undefined | ReactNode ); function rsvpAction() { window.open(event.eventUrl, "_blank"); } useEffect(() => { fetch( `${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => { if (response.ok) { setIconImage( <CityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); setSmallIconImage( <SmallCityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); } }); }, []); const date = new Date(event.dateTime); const eventDateString = `${WeekdayFormatter.format( date )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format( date )} at ${HourFormatter.format(date)}`; const descriptionString = event.
description.length > EVENT_DESCRIPTION_LENGTH ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + " ..." : event.description;
return ( <EventContainer> <BreakContainer> <IconBreakContainer> <DateContainer> <DateNumber>{DayFormatter.format(date)}</DateNumber> <DateMonth>{MonthShortFormatter.format(date)}</DateMonth> </DateContainer> <IconContainer>{iconImage}</IconContainer> </IconBreakContainer> <InfoContainer> <DateInfo> {smallIconImage} {eventDateString} </DateInfo> <EventInfo>{event.title}</EventInfo> <DescriptionInfo>{descriptionString}</DescriptionInfo> </InfoContainer> </BreakContainer> <RsvpContainer> <EventImage src={event.imageUrl} alt="rsvp" /> <RsvpBreakContainer> <CityContainer> <CityLabel> {event.venue?.city || event.group.city},{" "} {event.venue?.state.toUpperCase() || event.group.state.toUpperCase()} </CityLabel> </CityContainer> <AttendeeContainer> <PeopleIcon /> <AttendeeCount>{event.going}</AttendeeCount> <AttendeeLabel>attendees</AttendeeLabel> </AttendeeContainer> <CoffeeButton onClick={rsvpAction}> RSVP <ShareIcon /> </CoffeeButton> </RsvpBreakContainer> </RsvpContainer> </EventContainer> ); }
src/ui/calendar/coffee-event.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/service/notify.service.ts", "retrieved_chunk": " body: notification.message,\n recipient: channelSetting.email,\n subject: channelSetting.emailTitlePrepend\n ? `${channelSetting.emailTitlePrepend}${notification.title}`\n : notification.title,\n });\n }\n if (channelSetting.github) {\n await createIssue(channelSetting.github, {\n title: notification.title,", "score": 0.6455926895141602 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": " });\n } catch (e) {\n console.error(\n colors.blue.bold(\"REST Response \") +\n colors.yellow(options.name) +\n colors.red.bold(\" FAILURE\") +\n \"\\n\" +\n colors.yellow(`ERROR: ${e}`) +\n \"\\n\"\n );", "score": 0.6278467774391174 }, { "filename": "src/api/service/events.service.ts", "retrieved_chunk": "import { getMeetupEvents, MeetupEvent } from \"../dao/meetup.dao\";\nimport { getChapters } from \"../dao/settings.dao\";\n/**\n * Get a list of all upcoming events for Code and Coffee.\n */\nexport async function getEvents(): Promise<Array<MeetupEvent>> {\n const chapters = await getChapters();\n const events = await getMeetupEvents(chapters);\n return events.sort((a, b) => {\n return new Date(a.dateTime).getTime() - new Date(b.dateTime).getTime();", "score": 0.6226316094398499 }, { "filename": "src/api/util/request.util.ts", "retrieved_chunk": " colors.blue.bold(\"REST Response \") +\n colors.yellow(options.name) +\n colors.red.bold(\" FAILURE\") +\n \"\\n\" +\n colors.yellow(\n JSON.stringify({\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n })", "score": 0.6203881502151489 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " let newQuery = \"query {\";\n for (const i in chapters) {\n newQuery += `result${i}:groupByUrlname(urlname:\"${chapters[i].meetupGroupUrlName}\") { ...groupFragment }`;\n }\n newQuery += \"}\" + eventFragment + groupFragment;\n return newQuery;\n}\n/**\n * Process the response from the query and return a list of events.\n *", "score": 0.6185224056243896 } ]
typescript
description.length > EVENT_DESCRIPTION_LENGTH ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + " ..." : event.description;
import type { AbstractComponent, Component, Mixed } from "./component"; /** * `Provider<N, T, D>` represents a component provider. * @param N The name of the component. * @param T The type of the provided instance. * @param D The type of the dependencies. */ export type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{ // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider"; name: N; factory: Factory<T, D>; }>; export type Factory<T extends unknown, D extends unknown> = | FactoryFunction<T, D> | FactoryClass<T, D>; export type FactoryFunction<T extends unknown, D extends unknown> = (deps: D) => T; export type FactoryClass<T extends unknown, D extends unknown> = new (deps: D) => T; export function invokecFactory<T extends unknown, D extends unknown>( factory: Factory<T, D>, deps: D ): T { // check if the factory is a class (not a perfect check though) const desc = Object.getOwnPropertyDescriptor(factory, "prototype"); if (desc && !desc.writable) { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return new (factory as FactoryClass<T, D>)(deps); } else { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return (factory as FactoryFunction<T, D>)(deps); } } /** * The upper bound of provider types. */ export type AbstractProvider = Provider<string, unknown, never>; export type ProviderName<P extends AbstractProvider> = P extends Provider<infer N, unknown, never> ? N : never; export type ProviderDependencies<P extends AbstractProvider> = ( P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never ) extends (deps: infer I) => unknown ? I : never; export type ReconstructComponent<P extends AbstractProvider> = P extends Provider< infer N, infer T, never > ? Component<N, T> : never; export type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{ [K in keyof Ps]: ReconstructComponent<Ps[K]>; }>; /** * Returns the provider type that implements a component. * @param C A component. * @param Ds A list of dependencies. */ export type Impl< C extends AbstractComponent, Ds extends AbstractComponent[] = [],
> = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;
export type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs< Impl<C, Ds> >; type _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D> ? [name: N, factory: Factory<T, D>] : never; /** * Creates an implementation of a component. * @param name The name of the component. * @param factory A factory function or class that creates an instance of the component. * @returns An implementation (provider) of the component. */ export function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>( ...[name, factory]: ImplArgs<C, Ds> ): Impl<C, Ds> { const provider: AbstractProvider = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider", name, factory, }; // ImplArgs<C, Ds> and Impl<C, Ds> always have the same shape, so it's safe to cast. // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return provider as Impl<C, Ds>; }
src/provider.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.ts", "retrieved_chunk": " type: T;\n};\n/**\n * The upper bound of component types.\n */\nexport type AbstractComponent = Component<string, unknown>;\n/**\n * Returns the instance type of a component.\n * @param C A component.\n */", "score": 0.8872530460357666 }, { "filename": "src/mixer.ts", "retrieved_chunk": " * @param Ps A list of providers to be mixed.\n */\nexport type Mixer<Ps extends AbstractProvider[]> = Readonly<{\n /**\n * Extends the mixer with more providers.\n * @params providers Additional providers to be mixed.\n * @returns An extended mixer object.\n */\n with: MixerMethodWith<Ps>;\n /**", "score": 0.858769416809082 }, { "filename": "src/component.ts", "retrieved_chunk": "export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T>\n ? _Instance<N, T>\n : never;\ntype _Instance<N extends string, T extends unknown> = N extends unknown\n ? IsFiniteString<N> extends true\n ? { readonly [N0 in N]: T }\n : { readonly [N0 in N]?: T }\n : never;\n/**\n * Returns the mixed instance type of components.", "score": 0.8410094976425171 }, { "filename": "src/mixer.ts", "retrieved_chunk": " dependencies: MissingDependencies<P, Ps>;\n };\n };\ntype MissingDependencies<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = _MissingDependencies<ProviderDependencies<P>, MixedProvidedInstance<Ps>>;\ntype _MissingDependencies<D extends unknown, I extends unknown> = D extends unknown\n ? Wrap<\n {", "score": 0.8298240303993225 }, { "filename": "src/component.ts", "retrieved_chunk": " ...infer Xs extends AbstractComponent[],\n infer X extends AbstractComponent,\n ] ? _FilteredInstances<Xs, Is, Instance<X>, K>\n : [];\n// prettier-ignore\ntype _FilteredInstances<\n Cs extends AbstractComponent[],\n Is extends Array<{}>,\n I extends {},\n K extends string", "score": 0.8243483304977417 } ]
typescript
> = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;
import React, { useEffect, useState } from "react"; import { CoffeeEvent } from "./coffee-event"; import styled from "styled-components"; import { getEvents } from "./coffee.dao"; import { EventStats, getEventStats } from "./events.util"; import { CoffeeEventStats } from "./coffee-event-stats"; const CalendarContainer = styled.div` display: flex; flex-direction: column; height: ${({ height }: { height: number }) => height}px; padding: 15px; border-radius: 20px; box-shadow: 3px 3px 33px rgba(0, 0, 0, 0.04); @media (max-width: 600px) { padding: 0; } `; const EventTitle = styled.h1` @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap"); font-family: "Cormorant Garamond", serif; font-weight: 700; font-size: 36px; margin: 0 0 10px 0; `; const EventHolder = styled.div` border-top: 1px solid #dcdcdc; border-bottom: 1px solid #dcdcdc; overflow-y: scroll; padding-right: 20px; display: flex; flex-direction: column; align-items: center; /* width */ ::-webkit-scrollbar { width: 10px; transform: rotate(180deg); } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d4b9ff; border: 1px solid black; border-radius: 2px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #dbc4ff; border: 2px solid black; border-radius: 2px; } `; export function CoffeeCalendar({ height }: { height: number }) { const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>); const [showStats, setShowStats] = useState(false as boolean); const [stats, setStats] = useState(undefined as undefined | EventStats); useEffect(() => { getEvents().then((events) => { const newCoffeeEvents = [] as Array<JSX.Element>; for (const event of events) { if (event) { newCoffeeEvents.push(<CoffeeEvent event={event} key={event.id} />); } } setCoffeeEvents(newCoffeeEvents); setStats(getEventStats(events)); }); }, []); useEffect(() => { function displayDialogListener(event: KeyboardEvent): void { if (event.code === "KeyI" && event.ctrlKey) { setShowStats(!showStats); } } document.addEventListener("keydown", displayDialogListener); return () => { document.removeEventListener("keydown", displayDialogListener); }; }, [showStats]); return ( <CalendarContainer height={height}> <EventTitle>Events</EventTitle> {showStats && stats &&
<CoffeeEventStats stats={stats} />}
<EventHolder>{coffeeEvents}</EventHolder> </CalendarContainer> ); }
src/ui/calendar/coffee-calendar.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-event-stats.tsx", "retrieved_chunk": "`;\nexport function CoffeeEventStats({ stats }: { stats: EventStats }) {\n return (\n <StatsContainer>\n <Stat>Events: {stats.totalEvents}</Stat>\n <Stat>RSVPS: {stats.totalRSVPs}</Stat>\n <Stat>Active Chapters: {stats.totalActiveChapters}</Stat>\n </StatsContainer>\n );\n}", "score": 0.7961961030960083 }, { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": "const EVENT_DESCRIPTION_LENGTH = 125;\nexport function CoffeeEvent({ event }: { event: MeetupEvent }) {\n const [iconImage, setIconImage] = useState(\n undefined as undefined | ReactNode\n );\n const [smallIconImage, setSmallIconImage] = useState(\n undefined as undefined | ReactNode\n );\n function rsvpAction() {\n window.open(event.eventUrl, \"_blank\");", "score": 0.7781303524971008 }, { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": " )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format(\n date\n )} at ${HourFormatter.format(date)}`;\n const descriptionString =\n event.description.length > EVENT_DESCRIPTION_LENGTH\n ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + \" ...\"\n : event.description;\n return (\n <EventContainer>\n <BreakContainer>", "score": 0.7522519826889038 }, { "filename": "src/ui/wc.util.tsx", "retrieved_chunk": " connectedCallback() {\n const attrs = attributes.reduce(\n (acc, key) =>\n Object.assign(acc, {\n [key]: this.getAttribute(key) ?? undefined,\n }),\n {}\n );\n this.root.render(\n <StyleSheetManager target={this.shadow}>", "score": 0.7097042202949524 }, { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": " }\n useEffect(() => {\n fetch(\n `${\n WebConf.rootHost\n }/info/chapter-icons/${event.group.urlname.toLowerCase()}`\n ).then((response) => {\n if (response.ok) {\n setIconImage(\n <CityIcon", "score": 0.7079522609710693 } ]
typescript
<CoffeeEventStats stats={stats} />}
import type { AbstractComponent, Component, Mixed } from "./component"; /** * `Provider<N, T, D>` represents a component provider. * @param N The name of the component. * @param T The type of the provided instance. * @param D The type of the dependencies. */ export type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{ // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider"; name: N; factory: Factory<T, D>; }>; export type Factory<T extends unknown, D extends unknown> = | FactoryFunction<T, D> | FactoryClass<T, D>; export type FactoryFunction<T extends unknown, D extends unknown> = (deps: D) => T; export type FactoryClass<T extends unknown, D extends unknown> = new (deps: D) => T; export function invokecFactory<T extends unknown, D extends unknown>( factory: Factory<T, D>, deps: D ): T { // check if the factory is a class (not a perfect check though) const desc = Object.getOwnPropertyDescriptor(factory, "prototype"); if (desc && !desc.writable) { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return new (factory as FactoryClass<T, D>)(deps); } else { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return (factory as FactoryFunction<T, D>)(deps); } } /** * The upper bound of provider types. */ export type AbstractProvider = Provider<string, unknown, never>; export type ProviderName<P extends AbstractProvider> = P extends Provider<infer N, unknown, never> ? N : never; export type ProviderDependencies<P extends AbstractProvider> = ( P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never ) extends (deps: infer I) => unknown ? I : never; export type ReconstructComponent<P extends AbstractProvider> = P extends Provider< infer N, infer T, never > ? Component<N, T> : never;
export type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{
[K in keyof Ps]: ReconstructComponent<Ps[K]>; }>; /** * Returns the provider type that implements a component. * @param C A component. * @param Ds A list of dependencies. */ export type Impl< C extends AbstractComponent, Ds extends AbstractComponent[] = [], > = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never; export type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs< Impl<C, Ds> >; type _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D> ? [name: N, factory: Factory<T, D>] : never; /** * Creates an implementation of a component. * @param name The name of the component. * @param factory A factory function or class that creates an instance of the component. * @returns An implementation (provider) of the component. */ export function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>( ...[name, factory]: ImplArgs<C, Ds> ): Impl<C, Ds> { const provider: AbstractProvider = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider", name, factory, }; // ImplArgs<C, Ds> and Impl<C, Ds> always have the same shape, so it's safe to cast. // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return provider as Impl<C, Ds>; }
src/provider.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/mixer.ts", "retrieved_chunk": " dependencies: MissingDependencies<P, Ps>;\n };\n };\ntype MissingDependencies<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = _MissingDependencies<ProviderDependencies<P>, MixedProvidedInstance<Ps>>;\ntype _MissingDependencies<D extends unknown, I extends unknown> = D extends unknown\n ? Wrap<\n {", "score": 0.8673882484436035 }, { "filename": "src/mixer.ts", "retrieved_chunk": " };\n };\ntype IncompatibleDependencies<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = _IncompatibleDependencies<ProviderDependencies<P>, MixedProvidedInstance<Ps>>;\ntype _IncompatibleDependencies<D extends unknown, I extends unknown> = D extends unknown\n ? Wrap<\n {\n [N in keyof D & keyof I]: I[N] extends D[N]", "score": 0.8628221750259399 }, { "filename": "src/component.ts", "retrieved_chunk": "export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T>\n ? _Instance<N, T>\n : never;\ntype _Instance<N extends string, T extends unknown> = N extends unknown\n ? IsFiniteString<N> extends true\n ? { readonly [N0 in N]: T }\n : { readonly [N0 in N]?: T }\n : never;\n/**\n * Returns the mixed instance type of components.", "score": 0.8548651337623596 }, { "filename": "src/mixer.ts", "retrieved_chunk": " * Creates a new mixed instance.\n * @returns A mixed instance.\n */\n new: MixerMethodNew<Ps>;\n}>;\ntype MixerMethodWith<Ps extends AbstractProvider[]> = <Qs extends AbstractProvider[]>(\n ...providers: Qs\n) => Mixer<[...Ps, ...Qs]>;\ntype MixerMethodNew<Ps extends AbstractProvider[]> = MixerError<Ps> extends never\n ? () => MixedProvidedInstance<Ps>", "score": 0.8278857469558716 }, { "filename": "src/component.ts", "retrieved_chunk": " ...infer Xs extends AbstractComponent[],\n infer X extends AbstractComponent,\n ] ? _FilteredInstances<Xs, Is, Instance<X>, K>\n : [];\n// prettier-ignore\ntype _FilteredInstances<\n Cs extends AbstractComponent[],\n Is extends Array<{}>,\n I extends {},\n K extends string", "score": 0.8247460126876831 } ]
typescript
export type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { AsString, IsFiniteString, Merge, OrElse, Prod, Wrap } from "./utils"; describe("IsFiniteString", () => { it("returns true if and only if the type has a finite number of inhabitants", () => { assertType<Equals<IsFiniteString<never>, true>>(); assertType<Equals<IsFiniteString<"foo">, true>>(); assertType<Equals<IsFiniteString<"foo" | "bar">, true>>(); assertType<Equals<IsFiniteString<string>, false>>(); assertType<Equals<IsFiniteString<`x-${string}`>, false>>(); assertType<Equals<IsFiniteString<`x-${number}`>, false>>(); assertType<Equals<IsFiniteString<`x-${bigint}`>, false>>(); assertType<Equals<IsFiniteString<`x-${boolean}`>, true>>(); assertType<Equals<IsFiniteString<"foo" | `x-${string}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${number}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${bigint}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${boolean}`>, true>>(); }); }); describe("AsString", () => { it("removes non-string components of a type", () => { assertType<Equals<AsString<never>, never>>(); assertType<Equals<AsString<string | number>, string>>(); assertType<Equals<AsString<"foo" | "bar" | 42>, "foo" | "bar">>(); }); }); describe("Prod", () => { it("returns the product type of the given tuple type", () => { assertType<Equals<Prod<[]>, unknown>>(); assertType<Equals<Prod<[{ foo: "foo" }, { bar: "bar" }]>, { foo: "foo" } & { bar: "bar" }>>(); assertType< Equals< Prod<[{ foo: "foo" } | { bar: "bar" }, { baz: "baz" }]>, ({ foo: "foo" } | { bar: "bar" }) & { baz: "baz" } > >(); assertType< Equals< Prod<[{ foo: "foo" }, { bar: "bar" } | { baz: "baz" }]>, { foo: "foo" } & ({ bar: "bar" } | { baz: "baz" }) > >(); }); it("distributes over union members", () => { assertType<Equals<Prod<never>, never>>(); assertType< Equals< Prod<[{ foo: "foo" }, { bar: "bar" }] | [{ baz: "baz" }, { qux: "qux" }]>, ({ foo: "foo" } & { bar: "bar" }) | ({ baz: "baz" } & { qux: "qux" }) > >(); }); }); describe("Merge", () => { it("merges an intersection type into a sinlge type", () => { assertType<Equals<Merge<{}>, {}>>(); assertType<Equals<Merge<{ foo: "foo" } & { bar: "bar" }>, { foo: "foo"; bar: "bar" }>>(); }); it("keeps the original property modifiers", () => { assertType< Equals<Merge<{ readonly foo: "foo" } & { bar?: "bar" }>, { readonly foo: "foo"; bar?: "bar" }> >(); }); it("distributes over union members", () => { assertType<Equals<Merge<never>, never>>(); assertType< Equals< Merge<({ foo: "foo" } & { bar: "bar" }) | ({ baz: "baz" } & { qux: "qux" })>, { foo: "foo"; bar: "bar" } | { baz: "baz"; qux: "qux" } > >(); }); }); describe("OrElse", () => { it("returns the first type if it is not `never`; otherwise, returns the second type", () => { assertType<Equals<
OrElse<never, "xxx">, "xxx">>();
assertType<Equals<OrElse<"foo", "xxx">, "foo">>(); assertType<Equals<OrElse<"foo" | "bar", "xxx">, "foo" | "bar">>(); }); }); describe("Wrap", () => { it("returns the type wrapped in a tupple if it is not `never`; otherwise, returns `never`", () => { assertType<Equals<Wrap<never>, never>>(); assertType<Equals<Wrap<"foo">, ["foo"]>>(); assertType<Equals<Wrap<"foo" | "bar">, ["foo" | "bar"]>>(); }); });
src/utils.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.spec.ts", "retrieved_chunk": "import type { Equals } from \"./__tests__/types\";\nimport { assertType } from \"./__tests__/types\";\nimport type { Component, Instance, Mixed } from \"./component\";\ndescribe(\"Instance\", () => {\n it(\"returns an object type with a property whose name is the component name and whose type is the component type\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n assertType<Equals<Instance<FooComponent>, Readonly<{ foo: { getFoo: () => number } }>>>();\n });\n it(\"returns the union type of object types if the component name is a union string\", () => {\n type XxxComponent = Component<never, { getXxx: () => number }>;", "score": 0.8531149625778198 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " assertType<Equals<ProviderName<FooProvider | BarProvider>, \"foo\" | \"bar\">>();\n });\n});\ndescribe(\"ProviderDependencies\", () => {\n it(\"returns the dependencies of the provider\", () => {\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n assertType<Equals<ProviderDependencies<FooProvider>, { bar: { getBar: () => string } }>>();\n });\n it(\"returns the intersection of the dependencies of all the union members\", () => {\n assertType<Equals<ProviderDependencies<never>, unknown>>();", "score": 0.8441897630691528 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " assertType<Equals<ProviderName<FooProvider>, \"foo\">>();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<ProviderName<never>, never>>();\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n type BarProvider = Provider<\n \"bar\",\n { getBar: () => string },\n { baz: { getBaz: () => boolean } }\n >;", "score": 0.8418567180633545 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n qux: { getQux: () => bigint };\n }>\n >\n >();\n });\n it(\"returns an empty object type if the input is not a tuple\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;", "score": 0.8402983546257019 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Instance<YyyComponent>,\n Readonly<{ [key: `x-${string}`]: { getYyy: () => number } | undefined }>\n >\n >();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<Instance<never>, never>>();\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n assertType<", "score": 0.8375454545021057 } ]
typescript
OrElse<never, "xxx">, "xxx">>();
import React, { useEffect, useState } from "react"; import { CoffeeEvent } from "./coffee-event"; import styled from "styled-components"; import { getEvents } from "./coffee.dao"; import { EventStats, getEventStats } from "./events.util"; import { CoffeeEventStats } from "./coffee-event-stats"; const CalendarContainer = styled.div` display: flex; flex-direction: column; height: ${({ height }: { height: number }) => height}px; padding: 15px; border-radius: 20px; box-shadow: 3px 3px 33px rgba(0, 0, 0, 0.04); @media (max-width: 600px) { padding: 0; } `; const EventTitle = styled.h1` @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap"); font-family: "Cormorant Garamond", serif; font-weight: 700; font-size: 36px; margin: 0 0 10px 0; `; const EventHolder = styled.div` border-top: 1px solid #dcdcdc; border-bottom: 1px solid #dcdcdc; overflow-y: scroll; padding-right: 20px; display: flex; flex-direction: column; align-items: center; /* width */ ::-webkit-scrollbar { width: 10px; transform: rotate(180deg); } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d4b9ff; border: 1px solid black; border-radius: 2px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #dbc4ff; border: 2px solid black; border-radius: 2px; } `; export function CoffeeCalendar({ height }: { height: number }) { const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>); const [showStats, setShowStats] = useState(false as boolean); const [stats, setStats] = useState(undefined as undefined | EventStats); useEffect(() => { getEvents().then((events) => { const newCoffeeEvents = [] as Array<JSX.Element>; for (const event of events) { if (event) { newCoffeeEvents.push(
<CoffeeEvent event={event} key={event.id} />);
} } setCoffeeEvents(newCoffeeEvents); setStats(getEventStats(events)); }); }, []); useEffect(() => { function displayDialogListener(event: KeyboardEvent): void { if (event.code === "KeyI" && event.ctrlKey) { setShowStats(!showStats); } } document.addEventListener("keydown", displayDialogListener); return () => { document.removeEventListener("keydown", displayDialogListener); }; }, [showStats]); return ( <CalendarContainer height={height}> <EventTitle>Events</EventTitle> {showStats && stats && <CoffeeEventStats stats={stats} />} <EventHolder>{coffeeEvents}</EventHolder> </CalendarContainer> ); }
src/ui/calendar/coffee-calendar.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": "const EVENT_DESCRIPTION_LENGTH = 125;\nexport function CoffeeEvent({ event }: { event: MeetupEvent }) {\n const [iconImage, setIconImage] = useState(\n undefined as undefined | ReactNode\n );\n const [smallIconImage, setSmallIconImage] = useState(\n undefined as undefined | ReactNode\n );\n function rsvpAction() {\n window.open(event.eventUrl, \"_blank\");", "score": 0.8208238482475281 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " * @param response The response from the query.\n */\nfunction processResponse(response: QueryResponse): Array<MeetupEvent> {\n const result = [] as Array<MeetupEvent>;\n for (const group of Object.values(response.data)) {\n if (group) {\n for (const event of group.upcomingEvents.edges) {\n result.push(event.node);\n }\n }", "score": 0.751128613948822 }, { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": " */\nexport function getEventStats(events: EventsResponse): EventStats {\n const result: EventStats = {\n totalEvents: 0,\n totalActiveChapters: 0,\n totalRSVPs: 0,\n };\n const chapters = new Set<string>();\n events.forEach((event) => {\n result.totalEvents++;", "score": 0.7504562139511108 }, { "filename": "src/ui/calendar/coffee-event-stats.tsx", "retrieved_chunk": "`;\nexport function CoffeeEventStats({ stats }: { stats: EventStats }) {\n return (\n <StatsContainer>\n <Stat>Events: {stats.totalEvents}</Stat>\n <Stat>RSVPS: {stats.totalRSVPs}</Stat>\n <Stat>Active Chapters: {stats.totalActiveChapters}</Stat>\n </StatsContainer>\n );\n}", "score": 0.7493634223937988 }, { "filename": "src/ui/wc.util.tsx", "retrieved_chunk": " connectedCallback() {\n const attrs = attributes.reduce(\n (acc, key) =>\n Object.assign(acc, {\n [key]: this.getAttribute(key) ?? undefined,\n }),\n {}\n );\n this.root.render(\n <StyleSheetManager target={this.shadow}>", "score": 0.7383801937103271 } ]
typescript
<CoffeeEvent event={event} key={event.id} />);
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { AsString, IsFiniteString, Merge, OrElse, Prod, Wrap } from "./utils"; describe("IsFiniteString", () => { it("returns true if and only if the type has a finite number of inhabitants", () => { assertType<Equals<IsFiniteString<never>, true>>(); assertType<Equals<IsFiniteString<"foo">, true>>(); assertType<Equals<IsFiniteString<"foo" | "bar">, true>>(); assertType<Equals<IsFiniteString<string>, false>>(); assertType<Equals<IsFiniteString<`x-${string}`>, false>>(); assertType<Equals<IsFiniteString<`x-${number}`>, false>>(); assertType<Equals<IsFiniteString<`x-${bigint}`>, false>>(); assertType<Equals<IsFiniteString<`x-${boolean}`>, true>>(); assertType<Equals<IsFiniteString<"foo" | `x-${string}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${number}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${bigint}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${boolean}`>, true>>(); }); }); describe("AsString", () => { it("removes non-string components of a type", () => { assertType<Equals<AsString<never>, never>>(); assertType<Equals<AsString<string | number>, string>>(); assertType<Equals<AsString<"foo" | "bar" | 42>, "foo" | "bar">>(); }); }); describe("Prod", () => { it("returns the product type of the given tuple type", () => { assertType<Equals<Prod<[]>, unknown>>(); assertType<Equals<Prod<[{ foo: "foo" }, { bar: "bar" }]>, { foo: "foo" } & { bar: "bar" }>>(); assertType< Equals< Prod<[{ foo: "foo" } | { bar: "bar" }, { baz: "baz" }]>, ({ foo: "foo" } | { bar: "bar" }) & { baz: "baz" } > >(); assertType< Equals< Prod<[{ foo: "foo" }, { bar: "bar" } | { baz: "baz" }]>, { foo: "foo" } & ({ bar: "bar" } | { baz: "baz" }) > >(); }); it("distributes over union members", () => { assertType<Equals<Prod<never>, never>>(); assertType< Equals< Prod<[{ foo: "foo" }, { bar: "bar" }] | [{ baz: "baz" }, { qux: "qux" }]>, ({ foo: "foo" } & { bar: "bar" }) | ({ baz: "baz" } & { qux: "qux" }) > >(); }); }); describe("Merge", () => { it("merges an intersection type into a sinlge type", () => {
assertType<Equals<Merge<{}>, {}>>();
assertType<Equals<Merge<{ foo: "foo" } & { bar: "bar" }>, { foo: "foo"; bar: "bar" }>>(); }); it("keeps the original property modifiers", () => { assertType< Equals<Merge<{ readonly foo: "foo" } & { bar?: "bar" }>, { readonly foo: "foo"; bar?: "bar" }> >(); }); it("distributes over union members", () => { assertType<Equals<Merge<never>, never>>(); assertType< Equals< Merge<({ foo: "foo" } & { bar: "bar" }) | ({ baz: "baz" } & { qux: "qux" })>, { foo: "foo"; bar: "bar" } | { baz: "baz"; qux: "qux" } > >(); }); }); describe("OrElse", () => { it("returns the first type if it is not `never`; otherwise, returns the second type", () => { assertType<Equals<OrElse<never, "xxx">, "xxx">>(); assertType<Equals<OrElse<"foo", "xxx">, "foo">>(); assertType<Equals<OrElse<"foo" | "bar", "xxx">, "foo" | "bar">>(); }); }); describe("Wrap", () => { it("returns the type wrapped in a tupple if it is not `never`; otherwise, returns `never`", () => { assertType<Equals<Wrap<never>, never>>(); assertType<Equals<Wrap<"foo">, ["foo"]>>(); assertType<Equals<Wrap<"foo" | "bar">, ["foo" | "bar"]>>(); }); });
src/utils.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n qux: { getQux: () => bigint };\n }>\n >\n >();\n });\n it(\"returns an empty object type if the input is not a tuple\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;", "score": 0.8408994078636169 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.8373574018478394 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " assertType<Equals<ProviderName<FooProvider | BarProvider>, \"foo\" | \"bar\">>();\n });\n});\ndescribe(\"ProviderDependencies\", () => {\n it(\"returns the dependencies of the provider\", () => {\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n assertType<Equals<ProviderDependencies<FooProvider>, { bar: { getBar: () => string } }>>();\n });\n it(\"returns the intersection of the dependencies of all the union members\", () => {\n assertType<Equals<ProviderDependencies<never>, unknown>>();", "score": 0.8320162296295166 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " assertType<Equals<ProviderName<FooProvider>, \"foo\">>();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<ProviderName<never>, never>>();\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n type BarProvider = Provider<\n \"bar\",\n { getBar: () => string },\n { baz: { getBaz: () => boolean } }\n >;", "score": 0.8317158222198486 }, { "filename": "src/component.spec.ts", "retrieved_chunk": "import type { Equals } from \"./__tests__/types\";\nimport { assertType } from \"./__tests__/types\";\nimport type { Component, Instance, Mixed } from \"./component\";\ndescribe(\"Instance\", () => {\n it(\"returns an object type with a property whose name is the component name and whose type is the component type\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n assertType<Equals<Instance<FooComponent>, Readonly<{ foo: { getFoo: () => number } }>>>();\n });\n it(\"returns the union type of object types if the component name is a union string\", () => {\n type XxxComponent = Component<never, { getXxx: () => number }>;", "score": 0.8286336660385132 } ]
typescript
assertType<Equals<Merge<{}>, {}>>();
import React, { ReactNode, useEffect, useState } from "react"; import styled from "styled-components"; import { People24Filled } from "@fluentui/react-icons"; import { Share24Filled } from "@fluentui/react-icons"; import { MeetupEvent } from "../../api/dao/meetup.dao"; import { WebConf } from "../web-conf"; const PeopleIcon = People24Filled; const ShareIcon = Share24Filled; const EventContainer = styled.div` @import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap"); font-family: "Source Sans Pro", sans-serif; display: flex; justify-content: space-between; flex-direction: row; gap: 15px; border-bottom: 1px solid #dcdcdc; padding-bottom: 15px; padding-top: 15px; width: 100%; @media (max-width: 600px) { flex-direction: column; gap: 10px; } `; const BreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { justify-content: left; } `; const DateContainer = styled.div` padding-top: 10px; display: flex; flex-direction: column; align-items: center; `; const DateNumber = styled.p` margin: 0; font-size: 24px; font-weight: 700; `; const DateMonth = styled.p` margin: 0; font-size: 15px; font-weight: 400; color: #6c6c6c; `; const IconContainer = styled.div` display: flex; flex-direction: column; width: 60px; `; const IconBreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { display: none; } `; const CityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; `; const SmallCityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; width: 30px; height: 30px; display: none; @media (max-width: 600px) { display: block; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; max-width: 400px; gap: 10px; @media (max-width: 600px) { align-items: center; } `; const DateInfo = styled.div` display: flex; flex-direction: row; font-weight: 400; color: #6c6c6c; font-size: 16px; margin: 0; align-items: end; gap: 10px; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const EventInfo = styled.p` font-weight: 700; font-size: 24px; margin: 0; @media (max-width: 600px) { font-size: 20px; text-align: center; } `; const DescriptionInfo = styled.p` color: #6c6c6c; font-weight: 400; margin: 0; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const RsvpContainer = styled.div` display: flex; flex-direction: column; align-items: end; @media (max-width: 600px) { flex-direction: row; justify-content: space-between; } `; const RsvpBreakContainer = styled.div` display: flex; flex-direction: column; `; const CityContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; width: 100%; `; const CityLabel = styled.p` font-weight: 400; margin: 0; font-size: 12px; color: #6c6c6c; `; const AttendeeContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; `; const AttendeeCount = styled.p` font-weight: 700; margin: 0 0 0 5px; font-size: 15px; `; const AttendeeLabel = styled.p` font-weight: 400; margin: 0; font-size: 15px; color: #6c6c6c; padding-left: 4px; `; const EventImage = styled.img` max-width: 111px; max-height: 74px; border-radius: 5px; `; const CoffeeButton = styled.button` display: flex; flex-direction: row; align-items: center; justify-content: center; background: #d4b9ff; gap: 10px; border: 1px solid #000000; border-radius: 5px; font-weight: 700; font-size: 15px; padding: 8px 16px; transition: background 0.2s, box-shadow 0.2s; :hover { background: #dbc4ff; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12); cursor: pointer; } :active { background: #a063ff; box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); } `; const MonthShortFormatter = new Intl.DateTimeFormat("default", { month: "short", }); const MonthLongFormatter = new Intl.DateTimeFormat("default", { month: "long", }); const WeekdayFormatter = new Intl.DateTimeFormat("default", { weekday: "long", }); const DayFormatter = new Intl.DateTimeFormat("default", { day: "numeric" }); const HourFormatter = new Intl.DateTimeFormat("default", { hour: "numeric", hour12: true, minute: "2-digit", }); const EVENT_DESCRIPTION_LENGTH = 125; export function CoffeeEvent({ event }: { event: MeetupEvent }) { const [iconImage, setIconImage] = useState( undefined as undefined | ReactNode ); const [smallIconImage, setSmallIconImage] = useState( undefined as undefined | ReactNode ); function rsvpAction() { window.open(event.eventUrl, "_blank"); } useEffect(() => { fetch( `${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => { if (response.ok) { setIconImage( <CityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); setSmallIconImage( <SmallCityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); } }); }, []);
const date = new Date(event.dateTime);
const eventDateString = `${WeekdayFormatter.format( date )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format( date )} at ${HourFormatter.format(date)}`; const descriptionString = event.description.length > EVENT_DESCRIPTION_LENGTH ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + " ..." : event.description; return ( <EventContainer> <BreakContainer> <IconBreakContainer> <DateContainer> <DateNumber>{DayFormatter.format(date)}</DateNumber> <DateMonth>{MonthShortFormatter.format(date)}</DateMonth> </DateContainer> <IconContainer>{iconImage}</IconContainer> </IconBreakContainer> <InfoContainer> <DateInfo> {smallIconImage} {eventDateString} </DateInfo> <EventInfo>{event.title}</EventInfo> <DescriptionInfo>{descriptionString}</DescriptionInfo> </InfoContainer> </BreakContainer> <RsvpContainer> <EventImage src={event.imageUrl} alt="rsvp" /> <RsvpBreakContainer> <CityContainer> <CityLabel> {event.venue?.city || event.group.city},{" "} {event.venue?.state.toUpperCase() || event.group.state.toUpperCase()} </CityLabel> </CityContainer> <AttendeeContainer> <PeopleIcon /> <AttendeeCount>{event.going}</AttendeeCount> <AttendeeLabel>attendees</AttendeeLabel> </AttendeeContainer> <CoffeeButton onClick={rsvpAction}> RSVP <ShareIcon /> </CoffeeButton> </RsvpBreakContainer> </RsvpContainer> </EventContainer> ); }
src/ui/calendar/coffee-event.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": " url: `${AppConf.settingsBaseUrl}/notifications.json`,\n method: \"GET\",\n })\n ).json();\n}", "score": 0.7161635756492615 }, { "filename": "src/api/dao/github.dao.ts", "retrieved_chunk": " \"X-GitHub-Api-Version\": \"2022-11-28\",\n Authorization: `Bearer ${AppConf.githubAuthKey}`,\n Accept: \"application/vnd.github+json\",\n },\n body: issue,\n })\n ).json();\n}", "score": 0.6622375249862671 }, { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": " await request({\n name: \"Chapters Setting\",\n url: `${AppConf.settingsBaseUrl}/chapters.json`,\n method: \"GET\",\n })\n ).json()) as Chapter[];\n}\n/**\n * Get the icon for the given chapter.\n *", "score": 0.6483379602432251 }, { "filename": "src/api/index.ts", "retrieved_chunk": " return request.headers?.[\"x-api-key\"] === AppConf.apiKey;\n }\n return true;\n}", "score": 0.6400793790817261 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " let newQuery = \"query {\";\n for (const i in chapters) {\n newQuery += `result${i}:groupByUrlname(urlname:\"${chapters[i].meetupGroupUrlName}\") { ...groupFragment }`;\n }\n newQuery += \"}\" + eventFragment + groupFragment;\n return newQuery;\n}\n/**\n * Process the response from the query and return a list of events.\n *", "score": 0.6325307488441467 } ]
typescript
const date = new Date(event.dateTime);
import type { AsString, IsFiniteString, Merge, Prod } from "./utils"; /** * `Component<N, T>` represents a component. * @param N The name of the component. * @param T The type of the component instance. */ export type Component<N extends string, T extends unknown> = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Component"; name: N; type: T; }; /** * The upper bound of component types. */ export type AbstractComponent = Component<string, unknown>; /** * Returns the instance type of a component. * @param C A component. */ export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T> ? _Instance<N, T> : never; type _Instance<N extends string, T extends unknown> = N extends unknown ? IsFiniteString<N> extends true ? { readonly [N0 in N]: T } : { readonly [N0 in N]?: T } : never; /** * Returns the mixed instance type of components. * @param Cs Components. */ export type Mixed<Cs extends AbstractComponent[]> =
Merge<Prod<FilteredInstances<Cs, [], never>>>;
// prettier-ignore type FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, K extends string > = Cs extends [] ? Is : Cs extends [ ...infer Xs extends AbstractComponent[], infer X extends AbstractComponent, ] ? _FilteredInstances<Xs, Is, Instance<X>, K> : []; // prettier-ignore type _FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, I extends {}, K extends string > = I extends unknown ? keyof I extends K ? FilteredInstances<Cs, Is, K> : IsFiniteString<AsString<keyof I>> extends true ? FilteredInstances<Cs, [I, ...Is], K | AsString<keyof I>> : FilteredInstances<Cs, Is, K | AsString<keyof I>> : never;
src/component.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.ts", "retrieved_chunk": " : never;\nexport type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{\n [K in keyof Ps]: ReconstructComponent<Ps[K]>;\n}>;\n/**\n * Returns the provider type that implements a component.\n * @param C A component.\n * @param Ds A list of dependencies.\n */\nexport type Impl<", "score": 0.865462064743042 }, { "filename": "src/provider.ts", "retrieved_chunk": "import type { AbstractComponent, Component, Mixed } from \"./component\";\n/**\n * `Provider<N, T, D>` represents a component provider.\n * @param N The name of the component.\n * @param T The type of the provided instance.\n * @param D The type of the dependencies.\n */\nexport type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __type: \"hokemi.type.Provider\";", "score": 0.8426955938339233 }, { "filename": "src/provider.ts", "retrieved_chunk": " * Creates an implementation of a component.\n * @param name The name of the component.\n * @param factory A factory function or class that creates an instance of the component.\n * @returns An implementation (provider) of the component.\n */\nexport function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>(\n ...[name, factory]: ImplArgs<C, Ds>\n): Impl<C, Ds> {\n const provider: AbstractProvider = {\n // eslint-disable-next-line @typescript-eslint/naming-convention", "score": 0.8342568278312683 }, { "filename": "src/provider.ts", "retrieved_chunk": " C extends AbstractComponent,\n Ds extends AbstractComponent[] = [],\n> = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;\nexport type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs<\n Impl<C, Ds>\n>;\ntype _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D>\n ? [name: N, factory: Factory<T, D>]\n : never;\n/**", "score": 0.8310462832450867 }, { "filename": "src/provider.ts", "retrieved_chunk": " P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never\n) extends (deps: infer I) => unknown\n ? I\n : never;\nexport type ReconstructComponent<P extends AbstractProvider> = P extends Provider<\n infer N,\n infer T,\n never\n>\n ? Component<N, T>", "score": 0.8266252279281616 } ]
typescript
Merge<Prod<FilteredInstances<Cs, [], never>>>;
import React, { useEffect, useState } from "react"; import { CoffeeEvent } from "./coffee-event"; import styled from "styled-components"; import { getEvents } from "./coffee.dao"; import { EventStats, getEventStats } from "./events.util"; import { CoffeeEventStats } from "./coffee-event-stats"; const CalendarContainer = styled.div` display: flex; flex-direction: column; height: ${({ height }: { height: number }) => height}px; padding: 15px; border-radius: 20px; box-shadow: 3px 3px 33px rgba(0, 0, 0, 0.04); @media (max-width: 600px) { padding: 0; } `; const EventTitle = styled.h1` @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap"); font-family: "Cormorant Garamond", serif; font-weight: 700; font-size: 36px; margin: 0 0 10px 0; `; const EventHolder = styled.div` border-top: 1px solid #dcdcdc; border-bottom: 1px solid #dcdcdc; overflow-y: scroll; padding-right: 20px; display: flex; flex-direction: column; align-items: center; /* width */ ::-webkit-scrollbar { width: 10px; transform: rotate(180deg); } /* Track */ ::-webkit-scrollbar-track { background: #f1f1f1; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d4b9ff; border: 1px solid black; border-radius: 2px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #dbc4ff; border: 2px solid black; border-radius: 2px; } `; export function CoffeeCalendar({ height }: { height: number }) { const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>); const [showStats, setShowStats] = useState(false as boolean); const [stats, setStats] = useState(undefined as undefined | EventStats); useEffect(() => { getEvents().then((events) => { const newCoffeeEvents = [] as Array<JSX.Element>; for (const event of events) { if (event) { newCoffeeEvents.
push(<CoffeeEvent event={event} key={event.id} />);
} } setCoffeeEvents(newCoffeeEvents); setStats(getEventStats(events)); }); }, []); useEffect(() => { function displayDialogListener(event: KeyboardEvent): void { if (event.code === "KeyI" && event.ctrlKey) { setShowStats(!showStats); } } document.addEventListener("keydown", displayDialogListener); return () => { document.removeEventListener("keydown", displayDialogListener); }; }, [showStats]); return ( <CalendarContainer height={height}> <EventTitle>Events</EventTitle> {showStats && stats && <CoffeeEventStats stats={stats} />} <EventHolder>{coffeeEvents}</EventHolder> </CalendarContainer> ); }
src/ui/calendar/coffee-calendar.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-event.tsx", "retrieved_chunk": "const EVENT_DESCRIPTION_LENGTH = 125;\nexport function CoffeeEvent({ event }: { event: MeetupEvent }) {\n const [iconImage, setIconImage] = useState(\n undefined as undefined | ReactNode\n );\n const [smallIconImage, setSmallIconImage] = useState(\n undefined as undefined | ReactNode\n );\n function rsvpAction() {\n window.open(event.eventUrl, \"_blank\");", "score": 0.8190692663192749 }, { "filename": "src/ui/calendar/events.util.ts", "retrieved_chunk": " */\nexport function getEventStats(events: EventsResponse): EventStats {\n const result: EventStats = {\n totalEvents: 0,\n totalActiveChapters: 0,\n totalRSVPs: 0,\n };\n const chapters = new Set<string>();\n events.forEach((event) => {\n result.totalEvents++;", "score": 0.7508779764175415 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " * @param response The response from the query.\n */\nfunction processResponse(response: QueryResponse): Array<MeetupEvent> {\n const result = [] as Array<MeetupEvent>;\n for (const group of Object.values(response.data)) {\n if (group) {\n for (const event of group.upcomingEvents.edges) {\n result.push(event.node);\n }\n }", "score": 0.7474104762077332 }, { "filename": "src/ui/calendar/coffee-event-stats.tsx", "retrieved_chunk": "`;\nexport function CoffeeEventStats({ stats }: { stats: EventStats }) {\n return (\n <StatsContainer>\n <Stat>Events: {stats.totalEvents}</Stat>\n <Stat>RSVPS: {stats.totalRSVPs}</Stat>\n <Stat>Active Chapters: {stats.totalActiveChapters}</Stat>\n </StatsContainer>\n );\n}", "score": 0.741041898727417 }, { "filename": "src/ui/wc.util.tsx", "retrieved_chunk": " connectedCallback() {\n const attrs = attributes.reduce(\n (acc, key) =>\n Object.assign(acc, {\n [key]: this.getAttribute(key) ?? undefined,\n }),\n {}\n );\n this.root.render(\n <StyleSheetManager target={this.shadow}>", "score": 0.7350366115570068 } ]
typescript
push(<CoffeeEvent event={event} key={event.id} />);
import type { AbstractComponent, Component, Mixed } from "./component"; /** * `Provider<N, T, D>` represents a component provider. * @param N The name of the component. * @param T The type of the provided instance. * @param D The type of the dependencies. */ export type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{ // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider"; name: N; factory: Factory<T, D>; }>; export type Factory<T extends unknown, D extends unknown> = | FactoryFunction<T, D> | FactoryClass<T, D>; export type FactoryFunction<T extends unknown, D extends unknown> = (deps: D) => T; export type FactoryClass<T extends unknown, D extends unknown> = new (deps: D) => T; export function invokecFactory<T extends unknown, D extends unknown>( factory: Factory<T, D>, deps: D ): T { // check if the factory is a class (not a perfect check though) const desc = Object.getOwnPropertyDescriptor(factory, "prototype"); if (desc && !desc.writable) { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return new (factory as FactoryClass<T, D>)(deps); } else { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return (factory as FactoryFunction<T, D>)(deps); } } /** * The upper bound of provider types. */ export type AbstractProvider = Provider<string, unknown, never>; export type ProviderName<P extends AbstractProvider> = P extends Provider<infer N, unknown, never> ? N : never; export type ProviderDependencies<P extends AbstractProvider> = ( P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never ) extends (deps: infer I) => unknown ? I : never; export type ReconstructComponent<P extends AbstractProvider> = P extends Provider< infer N, infer T, never > ? Component<N, T> : never; export type MixedProvidedInstance<Ps extends AbstractProvider[
]> = Mixed<{
[K in keyof Ps]: ReconstructComponent<Ps[K]>; }>; /** * Returns the provider type that implements a component. * @param C A component. * @param Ds A list of dependencies. */ export type Impl< C extends AbstractComponent, Ds extends AbstractComponent[] = [], > = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never; export type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs< Impl<C, Ds> >; type _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D> ? [name: N, factory: Factory<T, D>] : never; /** * Creates an implementation of a component. * @param name The name of the component. * @param factory A factory function or class that creates an instance of the component. * @returns An implementation (provider) of the component. */ export function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>( ...[name, factory]: ImplArgs<C, Ds> ): Impl<C, Ds> { const provider: AbstractProvider = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider", name, factory, }; // ImplArgs<C, Ds> and Impl<C, Ds> always have the same shape, so it's safe to cast. // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return provider as Impl<C, Ds>; }
src/provider.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/mixer.ts", "retrieved_chunk": " dependencies: MissingDependencies<P, Ps>;\n };\n };\ntype MissingDependencies<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = _MissingDependencies<ProviderDependencies<P>, MixedProvidedInstance<Ps>>;\ntype _MissingDependencies<D extends unknown, I extends unknown> = D extends unknown\n ? Wrap<\n {", "score": 0.8601856231689453 }, { "filename": "src/mixer.ts", "retrieved_chunk": " };\n };\ntype IncompatibleDependencies<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = _IncompatibleDependencies<ProviderDependencies<P>, MixedProvidedInstance<Ps>>;\ntype _IncompatibleDependencies<D extends unknown, I extends unknown> = D extends unknown\n ? Wrap<\n {\n [N in keyof D & keyof I]: I[N] extends D[N]", "score": 0.8574283123016357 }, { "filename": "src/component.ts", "retrieved_chunk": "export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T>\n ? _Instance<N, T>\n : never;\ntype _Instance<N extends string, T extends unknown> = N extends unknown\n ? IsFiniteString<N> extends true\n ? { readonly [N0 in N]: T }\n : { readonly [N0 in N]?: T }\n : never;\n/**\n * Returns the mixed instance type of components.", "score": 0.8257550001144409 }, { "filename": "src/mixer.ts", "retrieved_chunk": " : MixerError<Ps>;\ntype MixerError<Ps extends AbstractProvider[]> = {\n [K in keyof Ps]: PerProviderError<Ps[K], Ps>;\n}[number];\ntype PerProviderError<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = MixedProvidedInstance<Ps> extends ProviderDependencies<P>\n ? never\n : OrElse<", "score": 0.8201016187667847 }, { "filename": "src/mixer.ts", "retrieved_chunk": " * Creates a new mixed instance.\n * @returns A mixed instance.\n */\n new: MixerMethodNew<Ps>;\n}>;\ntype MixerMethodWith<Ps extends AbstractProvider[]> = <Qs extends AbstractProvider[]>(\n ...providers: Qs\n) => Mixer<[...Ps, ...Qs]>;\ntype MixerMethodNew<Ps extends AbstractProvider[]> = MixerError<Ps> extends never\n ? () => MixedProvidedInstance<Ps>", "score": 0.8183274269104004 } ]
typescript
]> = Mixed<{
import React, { ReactNode, useEffect, useState } from "react"; import styled from "styled-components"; import { People24Filled } from "@fluentui/react-icons"; import { Share24Filled } from "@fluentui/react-icons"; import { MeetupEvent } from "../../api/dao/meetup.dao"; import { WebConf } from "../web-conf"; const PeopleIcon = People24Filled; const ShareIcon = Share24Filled; const EventContainer = styled.div` @import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap"); font-family: "Source Sans Pro", sans-serif; display: flex; justify-content: space-between; flex-direction: row; gap: 15px; border-bottom: 1px solid #dcdcdc; padding-bottom: 15px; padding-top: 15px; width: 100%; @media (max-width: 600px) { flex-direction: column; gap: 10px; } `; const BreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { justify-content: left; } `; const DateContainer = styled.div` padding-top: 10px; display: flex; flex-direction: column; align-items: center; `; const DateNumber = styled.p` margin: 0; font-size: 24px; font-weight: 700; `; const DateMonth = styled.p` margin: 0; font-size: 15px; font-weight: 400; color: #6c6c6c; `; const IconContainer = styled.div` display: flex; flex-direction: column; width: 60px; `; const IconBreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { display: none; } `; const CityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; `; const SmallCityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; width: 30px; height: 30px; display: none; @media (max-width: 600px) { display: block; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; max-width: 400px; gap: 10px; @media (max-width: 600px) { align-items: center; } `; const DateInfo = styled.div` display: flex; flex-direction: row; font-weight: 400; color: #6c6c6c; font-size: 16px; margin: 0; align-items: end; gap: 10px; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const EventInfo = styled.p` font-weight: 700; font-size: 24px; margin: 0; @media (max-width: 600px) { font-size: 20px; text-align: center; } `; const DescriptionInfo = styled.p` color: #6c6c6c; font-weight: 400; margin: 0; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const RsvpContainer = styled.div` display: flex; flex-direction: column; align-items: end; @media (max-width: 600px) { flex-direction: row; justify-content: space-between; } `; const RsvpBreakContainer = styled.div` display: flex; flex-direction: column; `; const CityContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; width: 100%; `; const CityLabel = styled.p` font-weight: 400; margin: 0; font-size: 12px; color: #6c6c6c; `; const AttendeeContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; `; const AttendeeCount = styled.p` font-weight: 700; margin: 0 0 0 5px; font-size: 15px; `; const AttendeeLabel = styled.p` font-weight: 400; margin: 0; font-size: 15px; color: #6c6c6c; padding-left: 4px; `; const EventImage = styled.img` max-width: 111px; max-height: 74px; border-radius: 5px; `; const CoffeeButton = styled.button` display: flex; flex-direction: row; align-items: center; justify-content: center; background: #d4b9ff; gap: 10px; border: 1px solid #000000; border-radius: 5px; font-weight: 700; font-size: 15px; padding: 8px 16px; transition: background 0.2s, box-shadow 0.2s; :hover { background: #dbc4ff; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12); cursor: pointer; } :active { background: #a063ff; box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); } `; const MonthShortFormatter = new Intl.DateTimeFormat("default", { month: "short", }); const MonthLongFormatter = new Intl.DateTimeFormat("default", { month: "long", }); const WeekdayFormatter = new Intl.DateTimeFormat("default", { weekday: "long", }); const DayFormatter = new Intl.DateTimeFormat("default", { day: "numeric" }); const HourFormatter = new Intl.DateTimeFormat("default", { hour: "numeric", hour12: true, minute: "2-digit", }); const EVENT_DESCRIPTION_LENGTH = 125; export function CoffeeEvent({ event }: { event: MeetupEvent }) { const [iconImage, setIconImage] = useState( undefined as undefined | ReactNode ); const [smallIconImage, setSmallIconImage] = useState( undefined as undefined | ReactNode ); function rsvpAction() { window.open(event.eventUrl, "_blank"); } useEffect(() => { fetch( `${
WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => {
if (response.ok) { setIconImage( <CityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); setSmallIconImage( <SmallCityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); } }); }, []); const date = new Date(event.dateTime); const eventDateString = `${WeekdayFormatter.format( date )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format( date )} at ${HourFormatter.format(date)}`; const descriptionString = event.description.length > EVENT_DESCRIPTION_LENGTH ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + " ..." : event.description; return ( <EventContainer> <BreakContainer> <IconBreakContainer> <DateContainer> <DateNumber>{DayFormatter.format(date)}</DateNumber> <DateMonth>{MonthShortFormatter.format(date)}</DateMonth> </DateContainer> <IconContainer>{iconImage}</IconContainer> </IconBreakContainer> <InfoContainer> <DateInfo> {smallIconImage} {eventDateString} </DateInfo> <EventInfo>{event.title}</EventInfo> <DescriptionInfo>{descriptionString}</DescriptionInfo> </InfoContainer> </BreakContainer> <RsvpContainer> <EventImage src={event.imageUrl} alt="rsvp" /> <RsvpBreakContainer> <CityContainer> <CityLabel> {event.venue?.city || event.group.city},{" "} {event.venue?.state.toUpperCase() || event.group.state.toUpperCase()} </CityLabel> </CityContainer> <AttendeeContainer> <PeopleIcon /> <AttendeeCount>{event.going}</AttendeeCount> <AttendeeLabel>attendees</AttendeeLabel> </AttendeeContainer> <CoffeeButton onClick={rsvpAction}> RSVP <ShareIcon /> </CoffeeButton> </RsvpBreakContainer> </RsvpContainer> </EventContainer> ); }
src/ui/calendar/coffee-event.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/api/dao/settings.dao.ts", "retrieved_chunk": " * @param chapter The chapter to get the icon for.\n */\nexport async function getChapterIcon(chapter: string): Promise<ArrayBuffer> {\n return await (\n await request({\n name: \"Chapter Icon\",\n url: `${AppConf.settingsBaseUrl}/chapter-icons/${chapter}.png`,\n method: \"GET\",\n })\n ).arrayBuffer();", "score": 0.6934859752655029 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": " const finalQuery = formQuery(chapters);\n const response = await request({\n name: \"Meetup Event\",\n url: `${AppConf.meetupApiBaseUrl}/gql`,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: { query: finalQuery },\n });\n return processResponse((await response.json()) as QueryResponse);\n}", "score": 0.671964168548584 }, { "filename": "src/api/dao/github.dao.ts", "retrieved_chunk": " repo: string,\n issue: GithubIssue\n): Promise<GithubIssueResponse> {\n return (\n await request({\n name: \"Create Github Issue\",\n url: `${AppConf.githubApiBaseUrl}/repos/${repo}/issues`,\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",", "score": 0.6529728770256042 }, { "filename": "src/ui/calendar/coffee-calendar.tsx", "retrieved_chunk": " useEffect(() => {\n function displayDialogListener(event: KeyboardEvent): void {\n if (event.code === \"KeyI\" && event.ctrlKey) {\n setShowStats(!showStats);\n }\n }\n document.addEventListener(\"keydown\", displayDialogListener);\n return () => {\n document.removeEventListener(\"keydown\", displayDialogListener);\n };", "score": 0.643166184425354 }, { "filename": "src/api/service/notify.service.ts", "retrieved_chunk": " body: notification.message,\n recipient: channelSetting.email,\n subject: channelSetting.emailTitlePrepend\n ? `${channelSetting.emailTitlePrepend}${notification.title}`\n : notification.title,\n });\n }\n if (channelSetting.github) {\n await createIssue(channelSetting.github, {\n title: notification.title,", "score": 0.6379600167274475 } ]
typescript
WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => {
import React, { ReactNode, useEffect, useState } from "react"; import styled from "styled-components"; import { People24Filled } from "@fluentui/react-icons"; import { Share24Filled } from "@fluentui/react-icons"; import { MeetupEvent } from "../../api/dao/meetup.dao"; import { WebConf } from "../web-conf"; const PeopleIcon = People24Filled; const ShareIcon = Share24Filled; const EventContainer = styled.div` @import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap"); font-family: "Source Sans Pro", sans-serif; display: flex; justify-content: space-between; flex-direction: row; gap: 15px; border-bottom: 1px solid #dcdcdc; padding-bottom: 15px; padding-top: 15px; width: 100%; @media (max-width: 600px) { flex-direction: column; gap: 10px; } `; const BreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { justify-content: left; } `; const DateContainer = styled.div` padding-top: 10px; display: flex; flex-direction: column; align-items: center; `; const DateNumber = styled.p` margin: 0; font-size: 24px; font-weight: 700; `; const DateMonth = styled.p` margin: 0; font-size: 15px; font-weight: 400; color: #6c6c6c; `; const IconContainer = styled.div` display: flex; flex-direction: column; width: 60px; `; const IconBreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { display: none; } `; const CityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; `; const SmallCityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; width: 30px; height: 30px; display: none; @media (max-width: 600px) { display: block; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; max-width: 400px; gap: 10px; @media (max-width: 600px) { align-items: center; } `; const DateInfo = styled.div` display: flex; flex-direction: row; font-weight: 400; color: #6c6c6c; font-size: 16px; margin: 0; align-items: end; gap: 10px; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const EventInfo = styled.p` font-weight: 700; font-size: 24px; margin: 0; @media (max-width: 600px) { font-size: 20px; text-align: center; } `; const DescriptionInfo = styled.p` color: #6c6c6c; font-weight: 400; margin: 0; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const RsvpContainer = styled.div` display: flex; flex-direction: column; align-items: end; @media (max-width: 600px) { flex-direction: row; justify-content: space-between; } `; const RsvpBreakContainer = styled.div` display: flex; flex-direction: column; `; const CityContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; width: 100%; `; const CityLabel = styled.p` font-weight: 400; margin: 0; font-size: 12px; color: #6c6c6c; `; const AttendeeContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; `; const AttendeeCount = styled.p` font-weight: 700; margin: 0 0 0 5px; font-size: 15px; `; const AttendeeLabel = styled.p` font-weight: 400; margin: 0; font-size: 15px; color: #6c6c6c; padding-left: 4px; `; const EventImage = styled.img` max-width: 111px; max-height: 74px; border-radius: 5px; `; const CoffeeButton = styled.button` display: flex; flex-direction: row; align-items: center; justify-content: center; background: #d4b9ff; gap: 10px; border: 1px solid #000000; border-radius: 5px; font-weight: 700; font-size: 15px; padding: 8px 16px; transition: background 0.2s, box-shadow 0.2s; :hover { background: #dbc4ff; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12); cursor: pointer; } :active { background: #a063ff; box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); } `; const MonthShortFormatter = new Intl.DateTimeFormat("default", { month: "short", }); const MonthLongFormatter = new Intl.DateTimeFormat("default", { month: "long", }); const WeekdayFormatter = new Intl.DateTimeFormat("default", { weekday: "long", }); const DayFormatter = new Intl.DateTimeFormat("default", { day: "numeric" }); const HourFormatter = new Intl.DateTimeFormat("default", { hour: "numeric", hour12: true, minute: "2-digit", }); const EVENT_DESCRIPTION_LENGTH = 125; export function CoffeeEvent({ event }: { event: MeetupEvent }) { const [iconImage, setIconImage] = useState( undefined as undefined | ReactNode ); const [smallIconImage, setSmallIconImage] = useState( undefined as undefined | ReactNode ); function rsvpAction() { window.open(event.eventUrl, "_blank"); } useEffect(() => { fetch( `${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => { if (response.ok) { setIconImage( <CityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); setSmallIconImage( <SmallCityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); } }); }, []); const date = new Date(event.dateTime); const eventDateString = `${WeekdayFormatter.format( date )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format( date )} at ${HourFormatter.format(date)}`; const descriptionString = event.description.length > EVENT_DESCRIPTION_LENGTH ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + " ..." : event.description; return ( <EventContainer> <BreakContainer> <IconBreakContainer> <DateContainer> <DateNumber>{DayFormatter.format(date)}</DateNumber> <DateMonth>{MonthShortFormatter.format(date)}</DateMonth> </DateContainer> <IconContainer>{iconImage}</IconContainer> </IconBreakContainer> <InfoContainer> <DateInfo> {smallIconImage} {eventDateString} </DateInfo> <EventInfo>{event.title}</EventInfo> <DescriptionInfo>{descriptionString}</DescriptionInfo> </InfoContainer> </BreakContainer> <RsvpContainer> <EventImage src={event.imageUrl} alt="rsvp" /> <RsvpBreakContainer> <CityContainer> <CityLabel>
{event.venue?.city || event.group.city},{" "}
{event.venue?.state.toUpperCase() || event.group.state.toUpperCase()} </CityLabel> </CityContainer> <AttendeeContainer> <PeopleIcon /> <AttendeeCount>{event.going}</AttendeeCount> <AttendeeLabel>attendees</AttendeeLabel> </AttendeeContainer> <CoffeeButton onClick={rsvpAction}> RSVP <ShareIcon /> </CoffeeButton> </RsvpBreakContainer> </RsvpContainer> </EventContainer> ); }
src/ui/calendar/coffee-event.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-calendar.tsx", "retrieved_chunk": " }, [showStats]);\n return (\n <CalendarContainer height={height}>\n <EventTitle>Events</EventTitle>\n {showStats && stats && <CoffeeEventStats stats={stats} />}\n <EventHolder>{coffeeEvents}</EventHolder>\n </CalendarContainer>\n );\n}", "score": 0.7760720252990723 }, { "filename": "src/ui/calendar/coffee-event-stats.tsx", "retrieved_chunk": "`;\nexport function CoffeeEventStats({ stats }: { stats: EventStats }) {\n return (\n <StatsContainer>\n <Stat>Events: {stats.totalEvents}</Stat>\n <Stat>RSVPS: {stats.totalRSVPs}</Stat>\n <Stat>Active Chapters: {stats.totalActiveChapters}</Stat>\n </StatsContainer>\n );\n}", "score": 0.695930540561676 }, { "filename": "src/api/index.ts", "retrieved_chunk": " headers: {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n };\n }\n}\nasync function handleRequest(\n event: APIGatewayProxyEventV2\n): Promise<APIGatewayProxyStructuredResultV2> {", "score": 0.5869341492652893 }, { "filename": "src/ui/calendar/coffee-calendar.tsx", "retrieved_chunk": " const newCoffeeEvents = [] as Array<JSX.Element>;\n for (const event of events) {\n if (event) {\n newCoffeeEvents.push(<CoffeeEvent event={event} key={event.id} />);\n }\n }\n setCoffeeEvents(newCoffeeEvents);\n setStats(getEventStats(events));\n });\n }, []);", "score": 0.5832518935203552 }, { "filename": "src/api/dao/meetup.dao.ts", "retrieved_chunk": "const eventFragment =\n \"fragment eventFragment on Event { id eventUrl title description going imageUrl venue { name address city state } dateTime group { id name city state urlname}}\";\nconst groupFragment =\n \"fragment groupFragment on Group { upcomingEvents(input:{first:10}) { edges { node { ...eventFragment } } } }\";\n/**\n * Form the query to get the events from the Meetup API.\n *\n * @param chapters The chapters to get events for.\n */\nfunction formQuery(chapters: Array<Chapter>): string {", "score": 0.573387622833252 } ]
typescript
{event.venue?.city || event.group.city},{" "}
import React, { ReactNode, useEffect, useState } from "react"; import styled from "styled-components"; import { People24Filled } from "@fluentui/react-icons"; import { Share24Filled } from "@fluentui/react-icons"; import { MeetupEvent } from "../../api/dao/meetup.dao"; import { WebConf } from "../web-conf"; const PeopleIcon = People24Filled; const ShareIcon = Share24Filled; const EventContainer = styled.div` @import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap"); font-family: "Source Sans Pro", sans-serif; display: flex; justify-content: space-between; flex-direction: row; gap: 15px; border-bottom: 1px solid #dcdcdc; padding-bottom: 15px; padding-top: 15px; width: 100%; @media (max-width: 600px) { flex-direction: column; gap: 10px; } `; const BreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { justify-content: left; } `; const DateContainer = styled.div` padding-top: 10px; display: flex; flex-direction: column; align-items: center; `; const DateNumber = styled.p` margin: 0; font-size: 24px; font-weight: 700; `; const DateMonth = styled.p` margin: 0; font-size: 15px; font-weight: 400; color: #6c6c6c; `; const IconContainer = styled.div` display: flex; flex-direction: column; width: 60px; `; const IconBreakContainer = styled.div` display: flex; flex-direction: row; justify-content: center; gap: 15px; @media (max-width: 600px) { display: none; } `; const CityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; `; const SmallCityIcon = styled.img` box-shadow: 0 0 16px 16px white inset; border-radius: 2px; width: 30px; height: 30px; display: none; @media (max-width: 600px) { display: block; } `; const InfoContainer = styled.div` display: flex; flex-direction: column; max-width: 400px; gap: 10px; @media (max-width: 600px) { align-items: center; } `; const DateInfo = styled.div` display: flex; flex-direction: row; font-weight: 400; color: #6c6c6c; font-size: 16px; margin: 0; align-items: end; gap: 10px; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const EventInfo = styled.p` font-weight: 700; font-size: 24px; margin: 0; @media (max-width: 600px) { font-size: 20px; text-align: center; } `; const DescriptionInfo = styled.p` color: #6c6c6c; font-weight: 400; margin: 0; @media (max-width: 600px) { font-size: 14px; text-align: center; } `; const RsvpContainer = styled.div` display: flex; flex-direction: column; align-items: end; @media (max-width: 600px) { flex-direction: row; justify-content: space-between; } `; const RsvpBreakContainer = styled.div` display: flex; flex-direction: column; `; const CityContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; width: 100%; `; const CityLabel = styled.p` font-weight: 400; margin: 0; font-size: 12px; color: #6c6c6c; `; const AttendeeContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; align-items: center; justify-content: center; `; const AttendeeCount = styled.p` font-weight: 700; margin: 0 0 0 5px; font-size: 15px; `; const AttendeeLabel = styled.p` font-weight: 400; margin: 0; font-size: 15px; color: #6c6c6c; padding-left: 4px; `; const EventImage = styled.img` max-width: 111px; max-height: 74px; border-radius: 5px; `; const CoffeeButton = styled.button` display: flex; flex-direction: row; align-items: center; justify-content: center; background: #d4b9ff; gap: 10px; border: 1px solid #000000; border-radius: 5px; font-weight: 700; font-size: 15px; padding: 8px 16px; transition: background 0.2s, box-shadow 0.2s; :hover { background: #dbc4ff; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12); cursor: pointer; } :active { background: #a063ff; box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); } `; const MonthShortFormatter = new Intl.DateTimeFormat("default", { month: "short", }); const MonthLongFormatter = new Intl.DateTimeFormat("default", { month: "long", }); const WeekdayFormatter = new Intl.DateTimeFormat("default", { weekday: "long", }); const DayFormatter = new Intl.DateTimeFormat("default", { day: "numeric" }); const HourFormatter = new Intl.DateTimeFormat("default", { hour: "numeric", hour12: true, minute: "2-digit", }); const EVENT_DESCRIPTION_LENGTH = 125; export function CoffeeEvent({ event }: { event: MeetupEvent }) { const [iconImage, setIconImage] = useState( undefined as undefined | ReactNode ); const [smallIconImage, setSmallIconImage] = useState( undefined as undefined | ReactNode ); function rsvpAction() {
window.open(event.eventUrl, "_blank");
} useEffect(() => { fetch( `${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}` ).then((response) => { if (response.ok) { setIconImage( <CityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); setSmallIconImage( <SmallCityIcon src={`${ WebConf.rootHost }/info/chapter-icons/${event.group.urlname.toLowerCase()}`} alt={`${event.group.city} Icon`} /> ); } }); }, []); const date = new Date(event.dateTime); const eventDateString = `${WeekdayFormatter.format( date )}, ${MonthLongFormatter.format(date)} ${DayFormatter.format( date )} at ${HourFormatter.format(date)}`; const descriptionString = event.description.length > EVENT_DESCRIPTION_LENGTH ? event.description.substring(0, EVENT_DESCRIPTION_LENGTH) + " ..." : event.description; return ( <EventContainer> <BreakContainer> <IconBreakContainer> <DateContainer> <DateNumber>{DayFormatter.format(date)}</DateNumber> <DateMonth>{MonthShortFormatter.format(date)}</DateMonth> </DateContainer> <IconContainer>{iconImage}</IconContainer> </IconBreakContainer> <InfoContainer> <DateInfo> {smallIconImage} {eventDateString} </DateInfo> <EventInfo>{event.title}</EventInfo> <DescriptionInfo>{descriptionString}</DescriptionInfo> </InfoContainer> </BreakContainer> <RsvpContainer> <EventImage src={event.imageUrl} alt="rsvp" /> <RsvpBreakContainer> <CityContainer> <CityLabel> {event.venue?.city || event.group.city},{" "} {event.venue?.state.toUpperCase() || event.group.state.toUpperCase()} </CityLabel> </CityContainer> <AttendeeContainer> <PeopleIcon /> <AttendeeCount>{event.going}</AttendeeCount> <AttendeeLabel>attendees</AttendeeLabel> </AttendeeContainer> <CoffeeButton onClick={rsvpAction}> RSVP <ShareIcon /> </CoffeeButton> </RsvpBreakContainer> </RsvpContainer> </EventContainer> ); }
src/ui/calendar/coffee-event.tsx
CodeandCoffeeCommunity-Code-and-Coffee-Website-Service-9539200
[ { "filename": "src/ui/calendar/coffee-calendar.tsx", "retrieved_chunk": " border: 2px solid black;\n border-radius: 2px;\n }\n`;\nexport function CoffeeCalendar({ height }: { height: number }) {\n const [coffeeEvents, setCoffeeEvents] = useState([] as Array<JSX.Element>);\n const [showStats, setShowStats] = useState(false as boolean);\n const [stats, setStats] = useState(undefined as undefined | EventStats);\n useEffect(() => {\n getEvents().then((events) => {", "score": 0.844656229019165 }, { "filename": "src/ui/calendar/coffee-calendar.tsx", "retrieved_chunk": " useEffect(() => {\n function displayDialogListener(event: KeyboardEvent): void {\n if (event.code === \"KeyI\" && event.ctrlKey) {\n setShowStats(!showStats);\n }\n }\n document.addEventListener(\"keydown\", displayDialogListener);\n return () => {\n document.removeEventListener(\"keydown\", displayDialogListener);\n };", "score": 0.7792881727218628 }, { "filename": "src/ui/wc.util.tsx", "retrieved_chunk": "import { createRoot, Root } from \"react-dom/client\";\nimport { StyleSheetManager } from \"styled-components\";\nimport React from \"react\";\nexport function registerReactWebComponent({\n name,\n Component,\n attributes = [],\n}: {\n name: string;\n Component: any;", "score": 0.7507286667823792 }, { "filename": "src/api/dao/email.dao.ts", "retrieved_chunk": "import { request } from \"../util/request.util\";\nimport { AppConf } from \"../app-conf\";\nexport type EmailContent = {\n recipient: string | Array<string>;\n subject: string;\n body: string;\n};\nexport async function sendEmail(email: EmailContent) {\n await request({\n name: \"Send Email\",", "score": 0.7503477931022644 }, { "filename": "src/api/controllers/chapter-icon.controller.ts", "retrieved_chunk": " await getChapterIcon(extractChapter(event.rawPath))\n ).toString(\"base64\"),\n headers: {\n \"Content-Type\": \"image/png\",\n },\n isBase64Encoded: true,\n };\n } catch (e: any | Response) {\n if (e.status === 404) {\n return {", "score": 0.7467007637023926 } ]
typescript
window.open(event.eventUrl, "_blank");
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Mixed } from "./component"; import type { Mixer } from "./mixer"; import { mixer } from "./mixer"; import type { Impl } from "./provider"; import { impl } from "./provider"; describe("Mixer", () => { describe("new", () => { /* eslint-disable @typescript-eslint/naming-convention */ type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("creates an instance if there is no error", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type M = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); it("reports missing dependencies if some dependencies are missing", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M["new"], | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "bar"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); }); it("reports incompatible dependencies if some dependencies are incompatible", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type Bar2 = { getBar2: () => string }; type Bar2Component = Component<"bar", Bar2>; type Bar2Impl = Impl<Bar2Component, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl, BazImpl, Bar2Impl]>; assertType< Equals< M["new"], { __incompatibleDependenciesError?: { reason: "some dependencies are incompatible"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; actualType: Bar2; }, ]; }; } > >(); }); it("reports missing dependencies if some dependencies are possibly missing", () => { type FooImpl = Impl<FooComponent, [BarComponent]>; type BarImpl = Impl<BarComponent>; type BarBazImpl = Impl<BarComponent | BazComponent>; type M1 = Mixer<[FooImpl, BarBazImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarBazImpl, BarImpl]>; assertType< Equals<M2["new"], () => Mixed<[FooComponent, BarComponent | BazComponent, BarComponent]>> >(); }); it("allows creating an instance if any possible combination of dependencies is provided", () => { type FooImpl = Impl<FooComponent, [BarComponent] | [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: | [ { name: "bar"; expectedType: Bar; }, ] | [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType<Equals<M2["new"], () => Mixed<[FooComponent, BarComponent]>>>(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType<Equals<M3["new"], () => Mixed<[FooComponent, BazComponent]>>>(); }); it("reports missing dependencies unless all possible dependencies are provided", () => { type FooImpl = Impl<FooComponent, [BarComponent]> | Impl<FooComponent, [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ | { name: "bar"; expectedType: Bar; } | { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M2["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType< Equals< M3["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M4 = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M4["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); /* eslint-enable @typescript-eslint/naming-convention */ }); }); describe("mixer", () => { type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("mixes components and creates a mixed instance", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, }));
const m = mixer(foo, bar, baz);
assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); it("overrides previous mixed components", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const baz2 = impl<BazComponent>("baz", () => ({ getBaz: () => false, })); const m = mixer(foo, bar, baz).with(baz2); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz, typeof baz2]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(42); }); it("throws if a component is referenced during its initialization", () => { // foo and bar reference each other during initialization const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", ({ foo }) => ({ getBar: () => foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).toThrow("'foo' is referenced during its initialization"); }); it("does not throw if a component is referenced after its initialization, even if there is a circular dependency", () => { // foo references bar during its initialization, while bar defers referencing foo until it is actually used // (this is not a good example though; it loops forever if you call foo.getFoo() or bar.getBar()) const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", deps => ({ getBar: () => deps.foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).not.toThrow(); }); it("accepts classes as compoent factories", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>( "foo", class FooImpl { private bar: Bar; private baz: Baz; constructor({ bar, baz }: Mixed<[BarComponent, BazComponent]>) { this.bar = bar; this.baz = baz; } getFoo(): number { return this.baz.getBaz() ? this.bar.getBar().length : 42; } } ); const bar = impl<BarComponent, [BazComponent]>( "bar", class BarImpl { private baz: Baz; constructor({ baz }: Mixed<[BazComponent]>) { this.baz = baz; } getBar(): string { return this.baz.getBaz() ? "Hello" : "Bye"; } } ); const baz = impl<BazComponent>( "baz", class BazImpl { getBaz(): boolean { return true; } } ); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); });
src/mixer.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.spec.ts", "retrieved_chunk": " type BarComponent = Component<\"bar\", { getBar: () => string }>;\n const foo = impl<FooComponent, [BarComponent]>(\"foo\", ({ bar }) => ({\n getFoo: () => bar.getBar().length,\n }));\n assertType<Equals<typeof foo, Impl<FooComponent, [BarComponent]>>>();\n expect(foo.name).toBe(\"foo\");\n const value = invokecFactory(foo.factory, {\n bar: {\n getBar: () => \"Hello\",\n },", "score": 0.9031586050987244 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " it(\"returns a provider type that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n Impl<FooComponent, [BarComponent, BazComponent]>,\n Provider<\n \"foo\",\n { getFoo: () => number },", "score": 0.8829929232597351 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.8798903226852417 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " });\n});\ndescribe(\"ImplArgs\", () => {\n it(\"returns a tuple that has the same shape of the provider that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n ImplArgs<FooComponent, [BarComponent, BazComponent]>,", "score": 0.8770287036895752 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n Mixed<[FooComponent, BarComponent, BazComponent]>,\n Readonly<{\n foo: { getFoo: () => number };\n bar: { getBar: () => string };\n baz: { getBaz: () => boolean };", "score": 0.8624235987663269 } ]
typescript
const m = mixer(foo, bar, baz);
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Instance, Mixed } from "./component"; describe("Instance", () => { it("returns an object type with a property whose name is the component name and whose type is the component type", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; assertType<Equals<Instance<FooComponent>, Readonly<{ foo: { getFoo: () => number } }>>>(); }); it("returns the union type of object types if the component name is a union string", () => { type XxxComponent = Component<never, { getXxx: () => number }>; assertType<Equals<Instance<XxxComponent>, never>>(); type FooComponent = Component<"foo1" | "foo2", { getFoo: () => number }>; assertType< Equals< Instance<FooComponent>, Readonly<{ foo1: { getFoo: () => number } }> | Readonly<{ foo2: { getFoo: () => number } }> > >(); }); it("returns an object type with an optional index signature if the component name is not of a finite string type", () => { type XxxComponent = Component<string, { getXxx: () => number }>; assertType< Equals< Instance<XxxComponent>, Readonly<{ [key: string]: { getXxx: () => number } | undefined }> > >(); type YyyComponent = Component<`x-${string}`, { getYyy: () => number }>; assertType< Equals< Instance<YyyComponent>, Readonly<{ [key: `x-${string}`]: { getYyy: () => number } | undefined }> > >(); }); it("distributes over union members", () => { assertType<Equals<Instance<never>, never>>(); type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; assertType< Equals< Instance<FooComponent | BarComponent>, Readonly<{ foo: { getFoo: () => number } }> | Readonly<{ bar: { getBar: () => string } }> > >(); }); }); describe("Mixed", () => { it("returns a mixed instance type of the components", () => { assertType<Equals<
Mixed<[]>, {}>>();
type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< Mixed<[FooComponent, BarComponent, BazComponent]>, Readonly<{ foo: { getFoo: () => number }; bar: { getBar: () => string }; baz: { getBaz: () => boolean }; }> > >(); }); it("overrides previously declared component instances", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; type Bar2Component = Component<"bar", { getBar2: () => bigint }>; assertType< Equals< Mixed<[FooComponent, BarComponent, BazComponent, Bar2Component]>, Readonly<{ foo: { getFoo: () => number }; bar: { getBar2: () => bigint }; baz: { getBaz: () => boolean }; }> > >(); }); it("erases all matching component instances before a component with an infinite name", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"x-baz", { getBaz: () => boolean }>; type QuxComponent = Component<"qux", { getQux: () => bigint }>; type XxxComponent = Component<string, { getXxx: () => number }>; type YyyComponent = Component<`x-${string}`, { getYyy: () => number }>; assertType< Equals< Mixed<[FooComponent, XxxComponent, BarComponent, BazComponent, YyyComponent, QuxComponent]>, Readonly<{ bar: { getBar: () => string }; qux: { getQux: () => bigint }; }> > >(); }); it("returns an empty object type if the input is not a tuple", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; assertType<Equals<Mixed<FooComponent[]>, {}>>(); assertType<Equals<Mixed<[...FooComponent[], BarComponent]>, {}>>(); assertType<Equals<Mixed<[FooComponent, ...BarComponent[]]>, {}>>(); }); it("distibutes over union members", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< Mixed<[FooComponent, BarComponent] | [BazComponent]>, | Readonly<{ foo: { getFoo: () => number }; bar: { getBar: () => string }; }> | Readonly<{ baz: { getBaz: () => boolean }; }> > >(); }); });
src/component.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.9444788694381714 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n baz: { getBaz: () => boolean };\n }>\n >\n >\n >();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<Impl<never, [BazComponent]>, never>>();", "score": 0.9342668056488037 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " >();\n });\n});\ndescribe(\"MixedProvidedInstance\", () => {\n it(\"returns a mixed instance type of the providers\", () => {\n assertType<Equals<MixedProvidedInstance<[]>, {}>>();\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n type BarProvider = Provider<\"bar\", { getBar: () => string }, {}>;\n type BazProvider = Provider<\"baz\", { getBaz: () => boolean }, {}>;\n assertType<", "score": 0.9248667359352112 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " >\n >();\n });\n});\ndescribe(\"ReconstructComponent\", () => {\n it(\"reconstructs a component type from the provider type\", () => {\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n assertType<\n Equals<ReconstructComponent<FooProvider>, Component<\"foo\", { getFoo: () => number }>>\n >();", "score": 0.9200212955474854 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " assertType<Equals<ProviderName<FooProvider>, \"foo\">>();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<ProviderName<never>, never>>();\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n type BarProvider = Provider<\n \"bar\",\n { getBar: () => string },\n { baz: { getBaz: () => boolean } }\n >;", "score": 0.9179118871688843 } ]
typescript
Mixed<[]>, {}>>();
import type { AbstractComponent, Component, Mixed } from "./component"; /** * `Provider<N, T, D>` represents a component provider. * @param N The name of the component. * @param T The type of the provided instance. * @param D The type of the dependencies. */ export type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{ // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider"; name: N; factory: Factory<T, D>; }>; export type Factory<T extends unknown, D extends unknown> = | FactoryFunction<T, D> | FactoryClass<T, D>; export type FactoryFunction<T extends unknown, D extends unknown> = (deps: D) => T; export type FactoryClass<T extends unknown, D extends unknown> = new (deps: D) => T; export function invokecFactory<T extends unknown, D extends unknown>( factory: Factory<T, D>, deps: D ): T { // check if the factory is a class (not a perfect check though) const desc = Object.getOwnPropertyDescriptor(factory, "prototype"); if (desc && !desc.writable) { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return new (factory as FactoryClass<T, D>)(deps); } else { // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return (factory as FactoryFunction<T, D>)(deps); } } /** * The upper bound of provider types. */ export type AbstractProvider = Provider<string, unknown, never>; export type ProviderName<P extends AbstractProvider> = P extends Provider<infer N, unknown, never> ? N : never; export type ProviderDependencies<P extends AbstractProvider> = ( P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never ) extends (deps: infer I) => unknown ? I : never; export type ReconstructComponent<P extends AbstractProvider> = P extends Provider< infer N, infer T, never > ? Component<N, T> : never; export type MixedProvidedInstance<Ps extends AbstractProvider[]>
= Mixed<{
[K in keyof Ps]: ReconstructComponent<Ps[K]>; }>; /** * Returns the provider type that implements a component. * @param C A component. * @param Ds A list of dependencies. */ export type Impl< C extends AbstractComponent, Ds extends AbstractComponent[] = [], > = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never; export type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs< Impl<C, Ds> >; type _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D> ? [name: N, factory: Factory<T, D>] : never; /** * Creates an implementation of a component. * @param name The name of the component. * @param factory A factory function or class that creates an instance of the component. * @returns An implementation (provider) of the component. */ export function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>( ...[name, factory]: ImplArgs<C, Ds> ): Impl<C, Ds> { const provider: AbstractProvider = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Provider", name, factory, }; // ImplArgs<C, Ds> and Impl<C, Ds> always have the same shape, so it's safe to cast. // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion return provider as Impl<C, Ds>; }
src/provider.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/mixer.ts", "retrieved_chunk": " dependencies: MissingDependencies<P, Ps>;\n };\n };\ntype MissingDependencies<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = _MissingDependencies<ProviderDependencies<P>, MixedProvidedInstance<Ps>>;\ntype _MissingDependencies<D extends unknown, I extends unknown> = D extends unknown\n ? Wrap<\n {", "score": 0.8633395433425903 }, { "filename": "src/mixer.ts", "retrieved_chunk": " };\n };\ntype IncompatibleDependencies<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = _IncompatibleDependencies<ProviderDependencies<P>, MixedProvidedInstance<Ps>>;\ntype _IncompatibleDependencies<D extends unknown, I extends unknown> = D extends unknown\n ? Wrap<\n {\n [N in keyof D & keyof I]: I[N] extends D[N]", "score": 0.8579750061035156 }, { "filename": "src/component.ts", "retrieved_chunk": "export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T>\n ? _Instance<N, T>\n : never;\ntype _Instance<N extends string, T extends unknown> = N extends unknown\n ? IsFiniteString<N> extends true\n ? { readonly [N0 in N]: T }\n : { readonly [N0 in N]?: T }\n : never;\n/**\n * Returns the mixed instance type of components.", "score": 0.8324870467185974 }, { "filename": "src/mixer.ts", "retrieved_chunk": " * Creates a new mixed instance.\n * @returns A mixed instance.\n */\n new: MixerMethodNew<Ps>;\n}>;\ntype MixerMethodWith<Ps extends AbstractProvider[]> = <Qs extends AbstractProvider[]>(\n ...providers: Qs\n) => Mixer<[...Ps, ...Qs]>;\ntype MixerMethodNew<Ps extends AbstractProvider[]> = MixerError<Ps> extends never\n ? () => MixedProvidedInstance<Ps>", "score": 0.8172879815101624 }, { "filename": "src/mixer.ts", "retrieved_chunk": " : MixerError<Ps>;\ntype MixerError<Ps extends AbstractProvider[]> = {\n [K in keyof Ps]: PerProviderError<Ps[K], Ps>;\n}[number];\ntype PerProviderError<\n P extends AbstractProvider,\n Ps extends AbstractProvider[],\n> = MixedProvidedInstance<Ps> extends ProviderDependencies<P>\n ? never\n : OrElse<", "score": 0.8101191520690918 } ]
typescript
= Mixed<{
import type { AsString, IsFiniteString, Merge, Prod } from "./utils"; /** * `Component<N, T>` represents a component. * @param N The name of the component. * @param T The type of the component instance. */ export type Component<N extends string, T extends unknown> = { // eslint-disable-next-line @typescript-eslint/naming-convention __type: "hokemi.type.Component"; name: N; type: T; }; /** * The upper bound of component types. */ export type AbstractComponent = Component<string, unknown>; /** * Returns the instance type of a component. * @param C A component. */ export type Instance<C extends AbstractComponent> = C extends Component<infer N, infer T> ? _Instance<N, T> : never; type _Instance<N extends string, T extends unknown> = N extends unknown ? IsFiniteString<N> extends true ? { readonly [N0 in N]: T } : { readonly [N0 in N]?: T } : never; /** * Returns the mixed instance type of components. * @param Cs Components. */ export type Mixed<Cs extends
AbstractComponent[]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;
// prettier-ignore type FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, K extends string > = Cs extends [] ? Is : Cs extends [ ...infer Xs extends AbstractComponent[], infer X extends AbstractComponent, ] ? _FilteredInstances<Xs, Is, Instance<X>, K> : []; // prettier-ignore type _FilteredInstances< Cs extends AbstractComponent[], Is extends Array<{}>, I extends {}, K extends string > = I extends unknown ? keyof I extends K ? FilteredInstances<Cs, Is, K> : IsFiniteString<AsString<keyof I>> extends true ? FilteredInstances<Cs, [I, ...Is], K | AsString<keyof I>> : FilteredInstances<Cs, Is, K | AsString<keyof I>> : never;
src/component.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.ts", "retrieved_chunk": " : never;\nexport type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{\n [K in keyof Ps]: ReconstructComponent<Ps[K]>;\n}>;\n/**\n * Returns the provider type that implements a component.\n * @param C A component.\n * @param Ds A list of dependencies.\n */\nexport type Impl<", "score": 0.8648281693458557 }, { "filename": "src/provider.ts", "retrieved_chunk": "import type { AbstractComponent, Component, Mixed } from \"./component\";\n/**\n * `Provider<N, T, D>` represents a component provider.\n * @param N The name of the component.\n * @param T The type of the provided instance.\n * @param D The type of the dependencies.\n */\nexport type Provider<N extends string, T extends unknown, D extends unknown> = Readonly<{\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __type: \"hokemi.type.Provider\";", "score": 0.8419179320335388 }, { "filename": "src/provider.ts", "retrieved_chunk": " * Creates an implementation of a component.\n * @param name The name of the component.\n * @param factory A factory function or class that creates an instance of the component.\n * @returns An implementation (provider) of the component.\n */\nexport function impl<C extends AbstractComponent, Ds extends AbstractComponent[] = []>(\n ...[name, factory]: ImplArgs<C, Ds>\n): Impl<C, Ds> {\n const provider: AbstractProvider = {\n // eslint-disable-next-line @typescript-eslint/naming-convention", "score": 0.8333837985992432 }, { "filename": "src/provider.ts", "retrieved_chunk": " C extends AbstractComponent,\n Ds extends AbstractComponent[] = [],\n> = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never;\nexport type ImplArgs<C extends AbstractComponent, Ds extends AbstractComponent[] = []> = _ImplArgs<\n Impl<C, Ds>\n>;\ntype _ImplArgs<P extends AbstractProvider> = P extends Provider<infer N, infer T, infer D>\n ? [name: N, factory: Factory<T, D>]\n : never;\n/**", "score": 0.8309726119041443 }, { "filename": "src/provider.ts", "retrieved_chunk": " P extends Provider<string, unknown, infer D> ? (deps: D) => unknown : never\n) extends (deps: infer I) => unknown\n ? I\n : never;\nexport type ReconstructComponent<P extends AbstractProvider> = P extends Provider<\n infer N,\n infer T,\n never\n>\n ? Component<N, T>", "score": 0.8265312314033508 } ]
typescript
AbstractComponent[]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Mixed } from "./component"; import type { Mixer } from "./mixer"; import { mixer } from "./mixer"; import type { Impl } from "./provider"; import { impl } from "./provider"; describe("Mixer", () => { describe("new", () => { /* eslint-disable @typescript-eslint/naming-convention */ type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("creates an instance if there is no error", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type M = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); it("reports missing dependencies if some dependencies are missing", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M["new"], | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "bar"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); }); it("reports incompatible dependencies if some dependencies are incompatible", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type Bar2 = { getBar2: () => string }; type Bar2Component = Component<"bar", Bar2>; type Bar2Impl = Impl<Bar2Component, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl, BazImpl, Bar2Impl]>; assertType< Equals< M["new"], { __incompatibleDependenciesError?: { reason: "some dependencies are incompatible"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; actualType: Bar2; }, ]; }; } > >(); }); it("reports missing dependencies if some dependencies are possibly missing", () => { type FooImpl = Impl<FooComponent, [BarComponent]>; type BarImpl = Impl<BarComponent>; type BarBazImpl = Impl<BarComponent | BazComponent>; type M1 = Mixer<[FooImpl, BarBazImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarBazImpl, BarImpl]>; assertType< Equals<M2["new"], () => Mixed<[FooComponent, BarComponent | BazComponent, BarComponent]>> >(); }); it("allows creating an instance if any possible combination of dependencies is provided", () => { type FooImpl = Impl<FooComponent, [BarComponent] | [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: | [ { name: "bar"; expectedType: Bar; }, ] | [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType<Equals<M2["new"], () => Mixed<[FooComponent, BarComponent]>>>(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType<Equals<M3["new"], () => Mixed<[FooComponent, BazComponent]>>>(); }); it("reports missing dependencies unless all possible dependencies are provided", () => { type FooImpl = Impl<FooComponent, [BarComponent]> | Impl<FooComponent, [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ | { name: "bar"; expectedType: Bar; } | { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M2["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType< Equals< M3["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M4 = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M4["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); /* eslint-enable @typescript-eslint/naming-convention */ }); }); describe("mixer", () => { type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("mixes components and creates a mixed instance", () => { const foo =
impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({
getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); it("overrides previous mixed components", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const baz2 = impl<BazComponent>("baz", () => ({ getBaz: () => false, })); const m = mixer(foo, bar, baz).with(baz2); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz, typeof baz2]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(42); }); it("throws if a component is referenced during its initialization", () => { // foo and bar reference each other during initialization const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", ({ foo }) => ({ getBar: () => foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).toThrow("'foo' is referenced during its initialization"); }); it("does not throw if a component is referenced after its initialization, even if there is a circular dependency", () => { // foo references bar during its initialization, while bar defers referencing foo until it is actually used // (this is not a good example though; it loops forever if you call foo.getFoo() or bar.getBar()) const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", deps => ({ getBar: () => deps.foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).not.toThrow(); }); it("accepts classes as compoent factories", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>( "foo", class FooImpl { private bar: Bar; private baz: Baz; constructor({ bar, baz }: Mixed<[BarComponent, BazComponent]>) { this.bar = bar; this.baz = baz; } getFoo(): number { return this.baz.getBaz() ? this.bar.getBar().length : 42; } } ); const bar = impl<BarComponent, [BazComponent]>( "bar", class BarImpl { private baz: Baz; constructor({ baz }: Mixed<[BazComponent]>) { this.baz = baz; } getBar(): string { return this.baz.getBaz() ? "Hello" : "Bye"; } } ); const baz = impl<BazComponent>( "baz", class BazImpl { getBaz(): boolean { return true; } } ); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); });
src/mixer.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.spec.ts", "retrieved_chunk": " it(\"returns a provider type that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n Impl<FooComponent, [BarComponent, BazComponent]>,\n Provider<\n \"foo\",\n { getFoo: () => number },", "score": 0.9414786696434021 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.9397855997085571 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " });\n});\ndescribe(\"ImplArgs\", () => {\n it(\"returns a tuple that has the same shape of the provider that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n ImplArgs<FooComponent, [BarComponent, BazComponent]>,", "score": 0.93708336353302 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.9182591438293457 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " it(\"erases all matching component instances before a component with an infinite name\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"x-baz\", { getBaz: () => boolean }>;\n type QuxComponent = Component<\"qux\", { getQux: () => bigint }>;\n type XxxComponent = Component<string, { getXxx: () => number }>;\n type YyyComponent = Component<`x-${string}`, { getYyy: () => number }>;\n assertType<\n Equals<\n Mixed<[FooComponent, XxxComponent, BarComponent, BazComponent, YyyComponent, QuxComponent]>,", "score": 0.9173961877822876 } ]
typescript
impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Mixed } from "./component"; import type { Mixer } from "./mixer"; import { mixer } from "./mixer"; import type { Impl } from "./provider"; import { impl } from "./provider"; describe("Mixer", () => { describe("new", () => { /* eslint-disable @typescript-eslint/naming-convention */ type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("creates an instance if there is no error", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type M = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); it("reports missing dependencies if some dependencies are missing", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M["new"], | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "bar"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); }); it("reports incompatible dependencies if some dependencies are incompatible", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type Bar2 = { getBar2: () => string }; type Bar2Component = Component<"bar", Bar2>; type Bar2Impl = Impl<Bar2Component, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl, BazImpl, Bar2Impl]>; assertType< Equals< M["new"], { __incompatibleDependenciesError?: { reason: "some dependencies are incompatible"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; actualType: Bar2; }, ]; }; } > >(); }); it("reports missing dependencies if some dependencies are possibly missing", () => { type FooImpl = Impl<FooComponent, [BarComponent]>; type BarImpl = Impl<BarComponent>; type BarBazImpl = Impl<BarComponent | BazComponent>; type M1 = Mixer<[FooImpl, BarBazImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarBazImpl, BarImpl]>; assertType< Equals<M2["new"], () => Mixed<[FooComponent, BarComponent | BazComponent, BarComponent]>> >(); }); it("allows creating an instance if any possible combination of dependencies is provided", () => { type FooImpl = Impl<FooComponent, [BarComponent] | [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: | [ { name: "bar"; expectedType: Bar; }, ] | [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType<Equals<M2["new"], () => Mixed<[FooComponent, BarComponent]>>>(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType<Equals<M3["new"], () => Mixed<[FooComponent, BazComponent]>>>(); }); it("reports missing dependencies unless all possible dependencies are provided", () => { type FooImpl = Impl<FooComponent, [BarComponent]> | Impl<FooComponent, [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ | { name: "bar"; expectedType: Bar; } | { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M2["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType< Equals< M3["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M4 = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M4["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); /* eslint-enable @typescript-eslint/naming-convention */ }); }); describe("mixer", () => { type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("mixes components and creates a mixed instance", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); it("overrides previous mixed components", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const baz2 = impl<BazComponent>("baz", () => ({ getBaz: () => false, })); const m = mixer(foo, bar, baz).with(baz2); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz, typeof baz2]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(42); }); it("throws if a component is referenced during its initialization", () => { // foo and bar reference each other during initialization const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", ({ foo }) => ({ getBar: () => foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).toThrow("'foo' is referenced during its initialization"); }); it("does not throw if a component is referenced after its initialization, even if there is a circular dependency", () => { // foo references bar during its initialization, while bar defers referencing foo until it is actually used // (this is not a good example though; it loops forever if you call foo.getFoo() or bar.getBar()) const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, }));
const bar = impl<BarComponent, [FooComponent]>("bar", deps => ({
getBar: () => deps.foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).not.toThrow(); }); it("accepts classes as compoent factories", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>( "foo", class FooImpl { private bar: Bar; private baz: Baz; constructor({ bar, baz }: Mixed<[BarComponent, BazComponent]>) { this.bar = bar; this.baz = baz; } getFoo(): number { return this.baz.getBaz() ? this.bar.getBar().length : 42; } } ); const bar = impl<BarComponent, [BazComponent]>( "bar", class BarImpl { private baz: Baz; constructor({ baz }: Mixed<[BazComponent]>) { this.baz = baz; } getBar(): string { return this.baz.getBaz() ? "Hello" : "Bye"; } } ); const baz = impl<BazComponent>( "baz", class BazImpl { getBaz(): boolean { return true; } } ); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); });
src/mixer.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n qux: { getQux: () => bigint };\n }>\n >\n >();\n });\n it(\"returns an empty object type if the input is not a tuple\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;", "score": 0.8534209728240967 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n baz: { getBaz: () => boolean };\n }>\n >\n >\n >();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<Impl<never, [BazComponent]>, never>>();", "score": 0.8514479398727417 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ProviderName,\n ReconstructComponent,\n} from \"./provider\";\nimport { invokecFactory, impl } from \"./provider\";\ndescribe(\"invokecFactory\", () => {\n it(\"calls the argument if it is a function\", () => {\n type Foo = { getFoo: () => number };\n const factory = (foo: number): Foo => ({ getFoo: () => foo });\n const value = invokecFactory(factory, 42);\n assertType<Equals<typeof value, Foo>>();", "score": 0.8505911827087402 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.8463670015335083 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.8447007536888123 } ]
typescript
const bar = impl<BarComponent, [FooComponent]>("bar", deps => ({
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component } from "./component"; import type { Factory, Impl, ImplArgs, MixedProvidedInstance, Provider, ProviderDependencies, ProviderName, ReconstructComponent, } from "./provider"; import { invokecFactory, impl } from "./provider"; describe("invokecFactory", () => { it("calls the argument if it is a function", () => { type Foo = { getFoo: () => number }; const factory = (foo: number): Foo => ({ getFoo: () => foo }); const value = invokecFactory(factory, 42); assertType<Equals<typeof value, Foo>>(); expect(value.getFoo()).toBe(42); }); it("calls the constructor of the argument if it is a class", () => { const factory = class Foo { private foo: number; constructor(foo: number) { this.foo = foo; } getFoo(): number { return this.foo; } }; const value = invokecFactory(factory, 42); assertType<Equals<typeof value, InstanceType<typeof factory>>>(); expect(value.getFoo()).toBe(42); }); }); describe("ProviderName", () => { it("returns the name of the provider", () => { type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; assertType<Equals<ProviderName<FooProvider>, "foo">>(); }); it("distributes over union members", () => { assertType<Equals<ProviderName<never>, never>>(); type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider< "bar", { getBar: () => string }, { baz: { getBaz: () => boolean } } >; assertType<Equals<ProviderName<FooProvider | BarProvider>, "foo" | "bar">>(); }); }); describe("ProviderDependencies", () => { it("returns the dependencies of the provider", () => { type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; assertType<Equals<ProviderDependencies<FooProvider>, { bar: { getBar: () => string } }>>(); }); it("returns the intersection of the dependencies of all the union members", () => { assertType<Equals<ProviderDependencies<never>, unknown>>(); type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider< "bar", { getBar: () => string }, { baz: { getBaz: () => boolean } } >; assertType< Equals< ProviderDependencies<FooProvider | BarProvider>, { bar: { getBar: () => string } } & { baz: { getBaz: () => boolean } } > >(); }); }); describe("ReconstructComponent", () => { it("reconstructs a component type from the provider type", () => { type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; assertType< Equals<ReconstructComponent
<FooProvider>, Component<"foo", { getFoo: () => number }>> >();
}); it("distributes over union members", () => { assertType<Equals<ReconstructComponent<never>, never>>(); type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider<"bar", { getBar: () => string }, {}>; assertType< Equals< ReconstructComponent<FooProvider | BarProvider>, Component<"foo", { getFoo: () => number }> | Component<"bar", { getBar: () => string }> > >(); }); }); describe("MixedProvidedInstance", () => { it("returns a mixed instance type of the providers", () => { assertType<Equals<MixedProvidedInstance<[]>, {}>>(); type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider<"bar", { getBar: () => string }, {}>; type BazProvider = Provider<"baz", { getBaz: () => boolean }, {}>; assertType< Equals< MixedProvidedInstance<[FooProvider, BarProvider, BazProvider]>, Readonly<{ foo: { getFoo: () => number }; bar: { getBar: () => string }; baz: { getBaz: () => boolean }; }> > >(); type Bar2Provider = Provider<"bar", { getBar2: () => string }, {}>; assertType< Equals< MixedProvidedInstance<[FooProvider, BarProvider, BazProvider, Bar2Provider]>, Readonly<{ foo: { getFoo: () => number }; bar: { getBar2: () => string }; baz: { getBaz: () => boolean }; }> > >(); }); it("distibutes over union members", () => { type FooProvider = Provider<"foo", { getFoo: () => number }, { bar: { getBar: () => string } }>; type BarProvider = Provider<"bar", { getBar: () => string }, {}>; type BazProvider = Provider<"baz", { getBaz: () => boolean }, {}>; assertType< Equals< MixedProvidedInstance<[FooProvider, BarProvider] | [BazProvider]>, | Readonly<{ foo: { getFoo: () => number }; bar: { getBar: () => string }; }> | Readonly<{ baz: { getBaz: () => boolean }; }> > >(); }); }); describe("Impl", () => { it("returns a provider type that implements the component", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< Impl<FooComponent, [BarComponent, BazComponent]>, Provider< "foo", { getFoo: () => number }, Readonly<{ bar: { getBar: () => string }; baz: { getBaz: () => boolean }; }> > > >(); }); it("distributes over union members", () => { assertType<Equals<Impl<never, [BazComponent]>, never>>(); type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< Impl<FooComponent | BarComponent, [BazComponent]>, | Provider<"foo", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>> | Provider<"bar", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>> > >(); }); }); describe("ImplArgs", () => { it("returns a tuple that has the same shape of the provider that implements the component", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< ImplArgs<FooComponent, [BarComponent, BazComponent]>, [ "foo", Factory< { getFoo: () => number }, Readonly<{ bar: { getBar: () => string }; baz: { getBaz: () => boolean }; }> >, ] > >(); }); it("distributes over union members", () => { assertType<Equals<ImplArgs<never, [BazComponent]>, never>>(); type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; type BazComponent = Component<"baz", { getBaz: () => boolean }>; assertType< Equals< ImplArgs<FooComponent | BarComponent, [BazComponent]>, | ["foo", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>] | ["bar", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>] > >(); }); }); describe("impl", () => { it("creates a provider that implements a component", () => { type FooComponent = Component<"foo", { getFoo: () => number }>; type BarComponent = Component<"bar", { getBar: () => string }>; const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); assertType<Equals<typeof foo, Impl<FooComponent, [BarComponent]>>>(); expect(foo.name).toBe("foo"); const value = invokecFactory(foo.factory, { bar: { getBar: () => "Hello", }, }); expect(value.getFoo()).toBe(5); }); });
src/provider.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.spec.ts", "retrieved_chunk": "import type { Equals } from \"./__tests__/types\";\nimport { assertType } from \"./__tests__/types\";\nimport type { Component, Instance, Mixed } from \"./component\";\ndescribe(\"Instance\", () => {\n it(\"returns an object type with a property whose name is the component name and whose type is the component type\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n assertType<Equals<Instance<FooComponent>, Readonly<{ foo: { getFoo: () => number } }>>>();\n });\n it(\"returns the union type of object types if the component name is a union string\", () => {\n type XxxComponent = Component<never, { getXxx: () => number }>;", "score": 0.9236857295036316 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Equals<\n Instance<FooComponent | BarComponent>,\n Readonly<{ foo: { getFoo: () => number } }> | Readonly<{ bar: { getBar: () => string } }>\n >\n >();\n });\n});\ndescribe(\"Mixed\", () => {\n it(\"returns a mixed instance type of the components\", () => {\n assertType<Equals<Mixed<[]>, {}>>();", "score": 0.9218186140060425 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.921009361743927 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n qux: { getQux: () => bigint };\n }>\n >\n >();\n });\n it(\"returns an empty object type if the input is not a tuple\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;", "score": 0.9128443002700806 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Instance<YyyComponent>,\n Readonly<{ [key: `x-${string}`]: { getYyy: () => number } | undefined }>\n >\n >();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<Instance<never>, never>>();\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n assertType<", "score": 0.9120631217956543 } ]
typescript
<FooProvider>, Component<"foo", { getFoo: () => number }>> >();
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { Component, Mixed } from "./component"; import type { Mixer } from "./mixer"; import { mixer } from "./mixer"; import type { Impl } from "./provider"; import { impl } from "./provider"; describe("Mixer", () => { describe("new", () => { /* eslint-disable @typescript-eslint/naming-convention */ type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("creates an instance if there is no error", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type M = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); it("reports missing dependencies if some dependencies are missing", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M["new"], | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } | { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "bar"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); }); it("reports incompatible dependencies if some dependencies are incompatible", () => { type FooImpl = Impl<FooComponent, [BarComponent, BazComponent]>; type BarImpl = Impl<BarComponent, [BazComponent]>; type BazImpl = Impl<BazComponent>; type Bar2 = { getBar2: () => string }; type Bar2Component = Component<"bar", Bar2>; type Bar2Impl = Impl<Bar2Component, [BazComponent]>; type M = Mixer<[FooImpl, BarImpl, BazImpl, Bar2Impl]>; assertType< Equals< M["new"], { __incompatibleDependenciesError?: { reason: "some dependencies are incompatible"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; actualType: Bar2; }, ]; }; } > >(); }); it("reports missing dependencies if some dependencies are possibly missing", () => { type FooImpl = Impl<FooComponent, [BarComponent]>; type BarImpl = Impl<BarComponent>; type BarBazImpl = Impl<BarComponent | BazComponent>; type M1 = Mixer<[FooImpl, BarBazImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarBazImpl, BarImpl]>; assertType< Equals<M2["new"], () => Mixed<[FooComponent, BarComponent | BazComponent, BarComponent]>> >(); }); it("allows creating an instance if any possible combination of dependencies is provided", () => { type FooImpl = Impl<FooComponent, [BarComponent] | [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: | [ { name: "bar"; expectedType: Bar; }, ] | [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType<Equals<M2["new"], () => Mixed<[FooComponent, BarComponent]>>>(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType<Equals<M3["new"], () => Mixed<[FooComponent, BazComponent]>>>(); }); it("reports missing dependencies unless all possible dependencies are provided", () => { type FooImpl = Impl<FooComponent, [BarComponent]> | Impl<FooComponent, [BazComponent]>; type BarImpl = Impl<BarComponent>; type BazImpl = Impl<BazComponent>; type M1 = Mixer<[FooImpl]>; assertType< Equals< M1["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ | { name: "bar"; expectedType: Bar; } | { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M2 = Mixer<[FooImpl, BarImpl]>; assertType< Equals< M2["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "baz"; expectedType: Baz; }, ]; }; } > >(); type M3 = Mixer<[FooImpl, BazImpl]>; assertType< Equals< M3["new"], { __missingDependenciesError?: { reason: "some dependencies are missing"; providerName: "foo"; dependencies: [ { name: "bar"; expectedType: Bar; }, ]; }; } > >(); type M4 = Mixer<[FooImpl, BarImpl, BazImpl]>; assertType<Equals<M4["new"], () => Mixed<[FooComponent, BarComponent, BazComponent]>>>(); }); /* eslint-enable @typescript-eslint/naming-convention */ }); }); describe("mixer", () => { type Foo = { getFoo: () => number }; type Bar = { getBar: () => string }; type Baz = { getBaz: () => boolean }; type FooComponent = Component<"foo", Foo>; type BarComponent = Component<"bar", Bar>; type BazComponent = Component<"baz", Baz>; it("mixes components and creates a mixed instance", () => {
const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({
getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); it("overrides previous mixed components", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ getFoo: () => (baz.getBaz() ? bar.getBar().length : 42), })); const bar = impl<BarComponent, [BazComponent]>("bar", ({ baz }) => ({ getBar: () => (baz.getBaz() ? "Hello" : "Bye"), })); const baz = impl<BazComponent>("baz", () => ({ getBaz: () => true, })); const baz2 = impl<BazComponent>("baz", () => ({ getBaz: () => false, })); const m = mixer(foo, bar, baz).with(baz2); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz, typeof baz2]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(42); }); it("throws if a component is referenced during its initialization", () => { // foo and bar reference each other during initialization const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", ({ foo }) => ({ getBar: () => foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).toThrow("'foo' is referenced during its initialization"); }); it("does not throw if a component is referenced after its initialization, even if there is a circular dependency", () => { // foo references bar during its initialization, while bar defers referencing foo until it is actually used // (this is not a good example though; it loops forever if you call foo.getFoo() or bar.getBar()) const foo = impl<FooComponent, [BarComponent]>("foo", ({ bar }) => ({ getFoo: () => bar.getBar().length, })); const bar = impl<BarComponent, [FooComponent]>("bar", deps => ({ getBar: () => deps.foo.getFoo().toString(), })); expect(() => { mixer(foo, bar).new(); }).not.toThrow(); }); it("accepts classes as compoent factories", () => { const foo = impl<FooComponent, [BarComponent, BazComponent]>( "foo", class FooImpl { private bar: Bar; private baz: Baz; constructor({ bar, baz }: Mixed<[BarComponent, BazComponent]>) { this.bar = bar; this.baz = baz; } getFoo(): number { return this.baz.getBaz() ? this.bar.getBar().length : 42; } } ); const bar = impl<BarComponent, [BazComponent]>( "bar", class BarImpl { private baz: Baz; constructor({ baz }: Mixed<[BazComponent]>) { this.baz = baz; } getBar(): string { return this.baz.getBaz() ? "Hello" : "Bye"; } } ); const baz = impl<BazComponent>( "baz", class BazImpl { getBaz(): boolean { return true; } } ); const m = mixer(foo, bar, baz); assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>(); const mixed = m.new(); assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>(); expect(mixed.foo.getFoo()).toBe(5); }); });
src/mixer.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/provider.spec.ts", "retrieved_chunk": " it(\"returns a provider type that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n Impl<FooComponent, [BarComponent, BazComponent]>,\n Provider<\n \"foo\",\n { getFoo: () => number },", "score": 0.9329484105110168 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " });\n});\ndescribe(\"ImplArgs\", () => {\n it(\"returns a tuple that has the same shape of the provider that implements the component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n assertType<\n Equals<\n ImplArgs<FooComponent, [BarComponent, BazComponent]>,", "score": 0.9310448169708252 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " }>\n >\n >();\n });\n it(\"overrides previously declared component instances\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n type BazComponent = Component<\"baz\", { getBaz: () => boolean }>;\n type Bar2Component = Component<\"bar\", { getBar2: () => bigint }>;\n assertType<", "score": 0.9300441741943359 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " ImplArgs<FooComponent | BarComponent, [BazComponent]>,\n | [\"foo\", Factory<{ getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n | [\"bar\", Factory<{ getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>]\n >\n >();\n });\n});\ndescribe(\"impl\", () => {\n it(\"creates a provider that implements a component\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;", "score": 0.913058876991272 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " });\n it(\"distibutes over union members\", () => {\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n type BarProvider = Provider<\"bar\", { getBar: () => string }, {}>;\n type BazProvider = Provider<\"baz\", { getBaz: () => boolean }, {}>;\n assertType<\n Equals<\n MixedProvidedInstance<[FooProvider, BarProvider] | [BazProvider]>,\n | Readonly<{\n foo: { getFoo: () => number };", "score": 0.9091866612434387 } ]
typescript
const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({
import { ScoreBoard } from 'mineflayer' import { createBot } from 'mineflayer' import { createFastWindowClicker } from './fastWindowClick' import { addLoggerToClientWriteFunction, initLogger, log, printMcChatToConsole } from './logger' import { clickWindow, isCoflChatMessage, removeMinecraftColorCodes, sleep } from './utils' import { onWebsocketCreateAuction } from './sellHandler' import { tradePerson } from './tradeHandler' import { swapProfile } from './swapProfileHandler' import { flipHandler } from './flipHandler' import { registerIngameMessageHandler } from './ingameMessageHandler' import { MyBot, TextMessageData } from '../types/autobuy' import { getConfigProperty, initConfigHelper, updatePersistentConfigProperty } from './configHelper' import { getSessionId } from './coflSessionManager' import { sendWebhookInitialized } from './webhookHandler' import { setupConsoleInterface } from './consoleHandler' import { initAFKHandler, tryToTeleportToIsland } from './AFKHandler' const WebSocket = require('ws') var prompt = require('prompt-sync')() initConfigHelper() initLogger() const version = '1.5.0-af' let wss: WebSocket let ingameName = getConfigProperty('INGAME_NAME') if (!ingameName) { ingameName = prompt('Enter your ingame name: ') updatePersistentConfigProperty('INGAME_NAME', ingameName) } const bot: MyBot = createBot({ username: ingameName, auth: 'microsoft', logErrors: true, version: '1.17', host: 'mc.hypixel.net' }) bot.setMaxListeners(0) bot.state = 'gracePeriod' createFastWindowClicker(bot._client) if (getConfigProperty('LOG_PACKAGES')) { addLoggerToClientWriteFunction(bot._client) } bot.once('login', connectWebsocket) bot.once('spawn', async () => { await bot.waitForChunksToLoad() await sleep(2000) bot.chat('/play sb') bot.on('scoreboardTitleChanged', onScoreboardChanged) registerIngameMessageHandler(bot, wss) }) function connectWebsocket() { wss
= new WebSocket(`wss://sky.coflnet.com/modsocket?player=${ingameName}&version=${version}&SId=${getSessionId(ingameName)}`) wss.onopen = function () {
setupConsoleInterface(wss) sendWebhookInitialized() } wss.onmessage = onWebsocketMessage wss.onclose = function (e) { log('Connection closed. Reconnecting... ', 'warn') setTimeout(function () { connectWebsocket() }, 1000) } wss.onerror = function (err) { log('Connection error: ' + JSON.stringify(err), 'error') wss.close() } } async function onWebsocketMessage(msg) { let message = JSON.parse(msg.data) let data = JSON.parse(message.data) switch (message.type) { case 'flip': log(message, 'debug') flipHandler(bot, data) break case 'chatMessage': for (let da of [...(data as TextMessageData[])]) { let isCoflChat = isCoflChatMessage(da.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole(da.text) } } break case 'writeToChat': let isCoflChat = isCoflChatMessage(data.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole((data as TextMessageData).text) } break case 'swapProfile': log(message, 'debug') swapProfile(bot, data) break case 'createAuction': log(message, 'debug') onWebsocketCreateAuction(bot, data) break case 'trade': log(message, 'debug') tradePerson(bot, wss, data) break case 'tradeResponse': let tradeDisplay = (bot.currentWindow.slots[39].nbt.value as any).display.value.Name.value if (tradeDisplay.includes('Deal!') || tradeDisplay.includes('Warning!')) { await sleep(3400) } clickWindow(bot, 39) break case 'getInventory': log('Uploading inventory...') wss.send( JSON.stringify({ type: 'uploadInventory', data: JSON.stringify(bot.inventory) }) ) break case 'execute': log(message, 'debug') bot.chat(data) break case 'privacySettings': log(message, 'debug') data.chatRegex = new RegExp(data.chatRegex) bot.privacySettings = data break } } async function onScoreboardChanged() { if ( bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, '')).find(e => e.includes('Purse:') || e.includes('Piggy:')) ) { bot.removeListener('scoreboardTitleChanged', onScoreboardChanged) log('Joined SkyBlock') initAFKHandler(bot) setTimeout(() => { log('Waited for grace period to end. Flips can now be bought.') bot.state = null bot.removeAllListeners('scoreboardTitleChanged') wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) }, 5500) await sleep(2500) tryToTeleportToIsland(bot, 0) } }
src/BAF.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/sellHandler.ts", "retrieved_chunk": " bot.state = null\n printMcChatToConsole(`§f[§4BAF§f]: §fItem listed: ${data.itemName} §ffor ${numberWithThousandsSeparators(data.price)} coins`)\n sendWebhookItemListed(data.itemName, numberWithThousandsSeparators(data.price), data.duration)\n bot.closeWindow(sellWindow)\n }\n}\nasync function setAuctionDuration(bot: MyBot, time: number) {\n log('setAuctionDuration function')\n return new Promise<void>(resolve => {\n bot._client.once('open_sign_entity', ({ location }) => {", "score": 0.6751964092254639 }, { "filename": "src/AFKHandler.ts", "retrieved_chunk": " if (\n !bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, '')).find(e => e.includes('Purse:') || e.includes('Piggy:'))\n ) {\n await sleep(delayBeforeTeleport)\n log(`Bot seems to be in lobby (Sidebar title = ${bot.scoreboard.sidebar.title}). Sending \"/play sb\"`)\n printMcChatToConsole('§f[§4BAF§f]: §fYou seem to be in the lobby.')\n printMcChatToConsole('§f[§4BAF§f]: §fWarping back into skyblock...')\n bot.chat('/play sb')\n return true\n }", "score": 0.6579122543334961 }, { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": " if (text.startsWith('You purchased')) {\n wss.send(\n JSON.stringify({\n type: 'uploadTab',\n data: JSON.stringify(Object.keys(bot.players).map(playername => bot.players[playername].displayName.getText(null)))\n })\n )\n wss.send(\n JSON.stringify({\n type: 'uploadScoreboard',", "score": 0.6445721387863159 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " }, 10000)\n let handler = function (window: any) {\n sellHandler(data, bot, window, () => {\n clearTimeout(timeout)\n bot.removeAllListeners('windowOpen')\n })\n }\n bot.on('windowOpen', handler)\n bot.chat('/ah')\n}", "score": 0.6214730739593506 }, { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": "import { MyBot } from '../types/autobuy'\nimport { log, printMcChatToConsole } from './logger'\nimport { clickWindow, getWindowTitle } from './utils'\nimport { ChatMessage } from 'prismarine-chat'\nimport { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler'\nexport function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) {\n bot.on('message', (message: ChatMessage, type) => {\n let text = message.getText(null)\n if (type == 'chat') {\n printMcChatToConsole(message.toAnsi())", "score": 0.6070799827575684 } ]
typescript
= new WebSocket(`wss://sky.coflnet.com/modsocket?player=${ingameName}&version=${version}&SId=${getSessionId(ingameName)}`) wss.onopen = function () {
import { ScoreBoard } from 'mineflayer' import { createBot } from 'mineflayer' import { createFastWindowClicker } from './fastWindowClick' import { addLoggerToClientWriteFunction, initLogger, log, printMcChatToConsole } from './logger' import { clickWindow, isCoflChatMessage, removeMinecraftColorCodes, sleep } from './utils' import { onWebsocketCreateAuction } from './sellHandler' import { tradePerson } from './tradeHandler' import { swapProfile } from './swapProfileHandler' import { flipHandler } from './flipHandler' import { registerIngameMessageHandler } from './ingameMessageHandler' import { MyBot, TextMessageData } from '../types/autobuy' import { getConfigProperty, initConfigHelper, updatePersistentConfigProperty } from './configHelper' import { getSessionId } from './coflSessionManager' import { sendWebhookInitialized } from './webhookHandler' import { setupConsoleInterface } from './consoleHandler' import { initAFKHandler, tryToTeleportToIsland } from './AFKHandler' const WebSocket = require('ws') var prompt = require('prompt-sync')() initConfigHelper() initLogger() const version = '1.5.0-af' let wss: WebSocket let ingameName = getConfigProperty('INGAME_NAME') if (!ingameName) { ingameName = prompt('Enter your ingame name: ') updatePersistentConfigProperty('INGAME_NAME', ingameName) } const bot: MyBot = createBot({ username: ingameName, auth: 'microsoft', logErrors: true, version: '1.17', host: 'mc.hypixel.net' }) bot.setMaxListeners(0) bot.state = 'gracePeriod' createFastWindowClicker(bot._client) if (getConfigProperty('LOG_PACKAGES')) { addLoggerToClientWriteFunction(bot._client) } bot.once('login', connectWebsocket) bot.once('spawn', async () => { await bot.waitForChunksToLoad() await sleep(2000) bot.chat('/play sb') bot.on('scoreboardTitleChanged', onScoreboardChanged) registerIngameMessageHandler(bot, wss) }) function connectWebsocket() { wss = new WebSocket(`wss://sky.coflnet.com/modsocket?player=${ingameName}&version=${version}&SId=${getSessionId(ingameName)}`) wss.onopen = function () { setupConsoleInterface(wss) sendWebhookInitialized() } wss.onmessage = onWebsocketMessage wss.onclose = function (e) { log('Connection closed. Reconnecting... ', 'warn') setTimeout(function () { connectWebsocket() }, 1000) } wss.onerror = function (err) { log('Connection error: ' + JSON.stringify(err), 'error') wss.close() } } async function onWebsocketMessage(msg) { let message = JSON.parse(msg.data) let data = JSON.parse(message.data) switch (message.type) { case 'flip': log(message, 'debug') flipHandler(bot, data) break case 'chatMessage': for (let da of [...(data as TextMessageData[])]) {
let isCoflChat = isCoflChatMessage(da.text) if (!isCoflChat) {
log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole(da.text) } } break case 'writeToChat': let isCoflChat = isCoflChatMessage(data.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole((data as TextMessageData).text) } break case 'swapProfile': log(message, 'debug') swapProfile(bot, data) break case 'createAuction': log(message, 'debug') onWebsocketCreateAuction(bot, data) break case 'trade': log(message, 'debug') tradePerson(bot, wss, data) break case 'tradeResponse': let tradeDisplay = (bot.currentWindow.slots[39].nbt.value as any).display.value.Name.value if (tradeDisplay.includes('Deal!') || tradeDisplay.includes('Warning!')) { await sleep(3400) } clickWindow(bot, 39) break case 'getInventory': log('Uploading inventory...') wss.send( JSON.stringify({ type: 'uploadInventory', data: JSON.stringify(bot.inventory) }) ) break case 'execute': log(message, 'debug') bot.chat(data) break case 'privacySettings': log(message, 'debug') data.chatRegex = new RegExp(data.chatRegex) bot.privacySettings = data break } } async function onScoreboardChanged() { if ( bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, '')).find(e => e.includes('Purse:') || e.includes('Piggy:')) ) { bot.removeListener('scoreboardTitleChanged', onScoreboardChanged) log('Joined SkyBlock') initAFKHandler(bot) setTimeout(() => { log('Waited for grace period to end. Flips can now be bought.') bot.state = null bot.removeAllListeners('scoreboardTitleChanged') wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) }, 5500) await sleep(2500) tryToTeleportToIsland(bot, 0) } }
src/BAF.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": "import { MyBot } from '../types/autobuy'\nimport { log, printMcChatToConsole } from './logger'\nimport { clickWindow, getWindowTitle } from './utils'\nimport { ChatMessage } from 'prismarine-chat'\nimport { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler'\nexport function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) {\n bot.on('message', (message: ChatMessage, type) => {\n let text = message.getText(null)\n if (type == 'chat') {\n printMcChatToConsole(message.toAnsi())", "score": 0.780443549156189 }, { "filename": "src/tradeHandler.ts", "retrieved_chunk": "import { MyBot, TradeData } from '../types/autobuy'\nimport { log } from './logger'\nimport { clickWindow, sleep } from './utils'\nexport async function tradePerson(bot: MyBot, websocket: WebSocket, data: TradeData) {\n let addedCoins = false\n let addedItems = false\n let trading = true\n while (trading) {\n bot.chat('/trade ' + data.target)\n bot.on('message', async msgE => {", "score": 0.7409559488296509 }, { "filename": "src/consoleHandler.ts", "retrieved_chunk": " rl.on('line', input => {\n if (input?.startsWith('/cofl') && input?.split(' ').length >= 2) {\n let splits = input.split(' ')\n splits.shift() // remove /cofl\n let command = splits.shift()\n ws.send(\n JSON.stringify({\n type: command,\n data: `\"${splits.join(' ')}\"`\n })", "score": 0.7312595844268799 }, { "filename": "src/swapProfileHandler.ts", "retrieved_chunk": "import { MyBot, SwapData } from '../types/autobuy'\nimport { log } from './logger'\nimport { clickWindow, getWindowTitle } from './utils'\nexport async function swapProfile(bot: MyBot, data: SwapData) {\n bot.setQuickBarSlot(8)\n bot.activateItem()\n bot.on('windowOpen', window => {\n let title = getWindowTitle(window)\n if (title == 'SkyBlock Menu') {\n clickWindow(bot, 48)", "score": 0.7229939699172974 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " }, 10000)\n let handler = function (window: any) {\n sellHandler(data, bot, window, () => {\n clearTimeout(timeout)\n bot.removeAllListeners('windowOpen')\n })\n }\n bot.on('windowOpen', handler)\n bot.chat('/ah')\n}", "score": 0.7209014892578125 } ]
typescript
let isCoflChat = isCoflChatMessage(da.text) if (!isCoflChat) {
import type { Equals } from "./__tests__/types"; import { assertType } from "./__tests__/types"; import type { AsString, IsFiniteString, Merge, OrElse, Prod, Wrap } from "./utils"; describe("IsFiniteString", () => { it("returns true if and only if the type has a finite number of inhabitants", () => { assertType<Equals<IsFiniteString<never>, true>>(); assertType<Equals<IsFiniteString<"foo">, true>>(); assertType<Equals<IsFiniteString<"foo" | "bar">, true>>(); assertType<Equals<IsFiniteString<string>, false>>(); assertType<Equals<IsFiniteString<`x-${string}`>, false>>(); assertType<Equals<IsFiniteString<`x-${number}`>, false>>(); assertType<Equals<IsFiniteString<`x-${bigint}`>, false>>(); assertType<Equals<IsFiniteString<`x-${boolean}`>, true>>(); assertType<Equals<IsFiniteString<"foo" | `x-${string}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${number}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${bigint}`>, false>>(); assertType<Equals<IsFiniteString<"foo" | `x-${boolean}`>, true>>(); }); }); describe("AsString", () => { it("removes non-string components of a type", () => { assertType<Equals<AsString<never>, never>>(); assertType<Equals<AsString<string | number>, string>>(); assertType<Equals<AsString<"foo" | "bar" | 42>, "foo" | "bar">>(); }); }); describe("Prod", () => { it("returns the product type of the given tuple type", () => { assertType<Equals<Prod<[]>, unknown>>(); assertType<Equals<Prod<[{ foo: "foo" }, { bar: "bar" }]>, { foo: "foo" } & { bar: "bar" }>>(); assertType< Equals< Prod<[{ foo: "foo" } | { bar: "bar" }, { baz: "baz" }]>, ({ foo: "foo" } | { bar: "bar" }) & { baz: "baz" } > >(); assertType< Equals< Prod<[{ foo: "foo" }, { bar: "bar" } | { baz: "baz" }]>, { foo: "foo" } & ({ bar: "bar" } | { baz: "baz" }) > >(); }); it("distributes over union members", () => { assertType<Equals<Prod<never>, never>>(); assertType< Equals< Prod<[{ foo: "foo" }, { bar: "bar" }] | [{ baz: "baz" }, { qux: "qux" }]>, ({ foo: "foo" } & { bar: "bar" }) | ({ baz: "baz" } & { qux: "qux" }) > >(); }); }); describe("Merge", () => { it("merges an intersection type into a sinlge type", () => { assertType<Equals<Merge<{}>, {}>>(); assertType<Equals<Merge<{ foo: "foo" } & { bar: "bar" }>, { foo: "foo"; bar: "bar" }>>(); }); it("keeps the original property modifiers", () => { assertType< Equals<Merge<{ readonly foo: "foo" } & { bar?: "bar" }>, { readonly foo: "foo"; bar?: "bar" }> >(); }); it("distributes over union members", () => { assertType<Equals<Merge<never>, never>>(); assertType< Equals< Merge<({ foo: "foo" } & { bar: "bar" }) | ({ baz: "baz" } & { qux: "qux" })>, { foo: "foo"; bar: "bar" } | { baz: "baz"; qux: "qux" } > >(); }); }); describe("OrElse", () => { it("returns the first type if it is not `never`; otherwise, returns the second type", () => { assertType<Equals
<OrElse<never, "xxx">, "xxx">>();
assertType<Equals<OrElse<"foo", "xxx">, "foo">>(); assertType<Equals<OrElse<"foo" | "bar", "xxx">, "foo" | "bar">>(); }); }); describe("Wrap", () => { it("returns the type wrapped in a tupple if it is not `never`; otherwise, returns `never`", () => { assertType<Equals<Wrap<never>, never>>(); assertType<Equals<Wrap<"foo">, ["foo"]>>(); assertType<Equals<Wrap<"foo" | "bar">, ["foo" | "bar"]>>(); }); });
src/utils.spec.ts
susisu-hokemi-0f7cbb0
[ { "filename": "src/component.spec.ts", "retrieved_chunk": "import type { Equals } from \"./__tests__/types\";\nimport { assertType } from \"./__tests__/types\";\nimport type { Component, Instance, Mixed } from \"./component\";\ndescribe(\"Instance\", () => {\n it(\"returns an object type with a property whose name is the component name and whose type is the component type\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n assertType<Equals<Instance<FooComponent>, Readonly<{ foo: { getFoo: () => number } }>>>();\n });\n it(\"returns the union type of object types if the component name is a union string\", () => {\n type XxxComponent = Component<never, { getXxx: () => number }>;", "score": 0.8520539999008179 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " assertType<Equals<ProviderName<FooProvider | BarProvider>, \"foo\" | \"bar\">>();\n });\n});\ndescribe(\"ProviderDependencies\", () => {\n it(\"returns the dependencies of the provider\", () => {\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n assertType<Equals<ProviderDependencies<FooProvider>, { bar: { getBar: () => string } }>>();\n });\n it(\"returns the intersection of the dependencies of all the union members\", () => {\n assertType<Equals<ProviderDependencies<never>, unknown>>();", "score": 0.843477725982666 }, { "filename": "src/provider.spec.ts", "retrieved_chunk": " assertType<Equals<ProviderName<FooProvider>, \"foo\">>();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<ProviderName<never>, never>>();\n type FooProvider = Provider<\"foo\", { getFoo: () => number }, { bar: { getBar: () => string } }>;\n type BarProvider = Provider<\n \"bar\",\n { getBar: () => string },\n { baz: { getBaz: () => boolean } }\n >;", "score": 0.8410369753837585 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Readonly<{\n bar: { getBar: () => string };\n qux: { getQux: () => bigint };\n }>\n >\n >();\n });\n it(\"returns an empty object type if the input is not a tuple\", () => {\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;", "score": 0.8382090330123901 }, { "filename": "src/component.spec.ts", "retrieved_chunk": " Instance<YyyComponent>,\n Readonly<{ [key: `x-${string}`]: { getYyy: () => number } | undefined }>\n >\n >();\n });\n it(\"distributes over union members\", () => {\n assertType<Equals<Instance<never>, never>>();\n type FooComponent = Component<\"foo\", { getFoo: () => number }>;\n type BarComponent = Component<\"bar\", { getBar: () => string }>;\n assertType<", "score": 0.8380002975463867 } ]
typescript
<OrElse<never, "xxx">, "xxx">>();
import { MyBot } from '../types/autobuy' import { log, printMcChatToConsole } from './logger' import { clickWindow, getWindowTitle } from './utils' import { ChatMessage } from 'prismarine-chat' import { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler' export function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) { bot.on('message', (message: ChatMessage, type) => { let text = message.getText(null) if (type == 'chat') { printMcChatToConsole(message.toAnsi()) if (text.startsWith('You purchased')) { wss.send( JSON.stringify({ type: 'uploadTab', data: JSON.stringify(Object.keys(bot.players).map(playername => bot.players[playername].displayName.getText(null))) }) ) wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) claimPurchased(bot) sendWebhookItemPurchased(text.split(' purchased ')[1].split(' for ')[0], text.split(' for ')[1].split(' coins!')[0]) } if (text.startsWith('[Auction]') && text.includes('bought') && text.includes('for')) { log('New item sold') claimSoldItem(bot, text.split(' bought ')[1].split(' for ')[0]) sendWebhookItemSold( text.split(' bought ')[1].split(' for ')[0], text.split(' for ')[1].split(' coins')[0], text.split('[Auction] ')[1].split(' bought ')[0] ) } if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) { wss.send( JSON.stringify({ type: 'chatBatch', data: JSON.stringify([text]) }) ) } } }) } function claimPurchased(bot: MyBot) { if (bot.state) { log('Currently busy with something else (' + bot.state + ') -> not claiming purchased item') setTimeout(() => { claimPurchased(bot) }, 1000) return } bot.state = 'claiming' bot.chat('/ah') setTimeout(() => { log('Claiming of purchased auction failed. Removing lock') bot.state = null }, 5000) bot.on('windowOpen', window => { let title =
getWindowTitle(window) log('Claiming auction window: ' + title) if (title.toString().includes('Auction House')) {
clickWindow(bot, 13) } if (title.toString().includes('Your Bids')) { let slotToClick = -1 for (let i = 0; i < window.slots.length; i++) { const slot = window.slots[i] let name = (slot?.nbt as any)?.value?.display?.value?.Name?.value?.toString() if (slot?.type === 380 && name?.includes('Claim') && name?.includes('All')) { log('Found cauldron to claim all purchased auctions -> clicking index ' + i) clickWindow(bot, i) bot.removeAllListeners('windowOpen') bot.state = null return } let lore = (slot?.nbt as any)?.value?.display?.value?.Lore?.value?.value?.toString() if (lore?.includes('Status:') && lore?.includes('Sold!')) { log('Found claimable purchased auction. Gonna click index ' + i) log(JSON.stringify(slot)) slotToClick = i } } clickWindow(bot, slotToClick) } if (title.toString().includes('BIN Auction View')) { if (!window.slots[31]) { log('Weird error trying to claim purchased auction', 'warn') log(window.title) log(JSON.stringify(window.slots)) bot.removeAllListeners('windowOpen') bot.state = null return } if (window.slots[31].name.includes('gold_block')) { log('Claiming purchased auction...') clickWindow(bot, 31) } bot.removeAllListeners('windowOpen') bot.state = null } }) } async function claimSoldItem(bot: MyBot, itemName: string) { if (bot.state) { log('Currently busy with something else (' + bot.state + ') -> not claiming sold item') setTimeout(() => { claimSoldItem(bot, itemName) }, 1000) return } let timeout = setTimeout(() => { log('Seems something went wrong while claiming sold item. Removing lock') bot.state = null bot.removeAllListeners('windowOpen') }, 10000) bot.state = 'claiming' bot.chat('/ah') bot.on('windowOpen', window => { let title = getWindowTitle(window) if (title.toString().includes('Auction House')) { clickWindow(bot, 15) } if (title.toString().includes('Manage Auctions')) { log('Claiming sold auction...') let clickSlot for (let i = 0; i < window.slots.length; i++) { const item = window.slots[i] as any if (item?.nbt?.value?.display?.value?.Lore && JSON.stringify(item.nbt.value.display.value.Lore).includes('Sold for')) { clickSlot = item.slot } if (item && item.type === 380 && (item.nbt as any).value?.display?.value?.Name?.value?.toString().includes('Claim All')) { log(item) log('Found cauldron to claim all sold auctions -> clicking index ' + item.slot) clickWindow(bot, item.slot) clearTimeout(timeout) bot.removeAllListeners('windowOpen') bot.state = null return } } log('Clicking auction to claim, index: ' + clickSlot) log(JSON.stringify(window.slots[clickSlot])) clickWindow(bot, clickSlot) } if (title == 'BIN Auction View') { if (window.slots[31].name.includes('gold_block')) { log('Clicking slot 31, claiming purchased auction') clickWindow(bot, 31) } clearTimeout(timeout) bot.removeAllListeners('windowOpen') bot.state = null } }) }
src/ingameMessageHandler.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/sellHandler.ts", "retrieved_chunk": " } catch (e) {\n log('Checking if correct price was set in sellHandler through an error: ' + JSON.stringify(e), 'error')\n }\n clickWindow(bot, 29)\n }\n }\n if (title == 'Auction Duration') {\n setAuctionDuration(bot, data.duration).then(() => {\n durationSet = true\n })", "score": 0.8555538654327393 }, { "filename": "src/tradeHandler.ts", "retrieved_chunk": " } else if (msg.startsWith('You have sent a trade request to ')) {\n log('successfully sent trade, waiting for them to accept')\n bot.on('windowOpen', async window => {\n trading = false\n log('Trade window opened')\n if (!addedItems) {\n for (let slot of data.slots) {\n slot += 44\n clickWindow(bot, slot)\n log('Clicked slot ' + slot)", "score": 0.8536306619644165 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " bot.state = 'selling'\n log('Selling item...')\n log(data)\n sellItem(data, bot)\n}\nasync function sellItem(data: SellData, bot: MyBot) {\n let timeout = setTimeout(() => {\n log('Seems something went wrong while selling. Removing lock', 'warn')\n bot.state = null\n bot.removeAllListeners('windowOpen')", "score": 0.8497493267059326 }, { "filename": "src/flipHandler.ts", "retrieved_chunk": " }\n}\nasync function useRegularPurchase(bot: MyBot) {\n bot.addListener('windowOpen', async window => {\n let title = getWindowTitle(window)\n if (title.toString().includes('BIN Auction View')) {\n await sleep(getConfigProperty('FLIP_ACTION_DELAY'))\n clickWindow(bot, 31)\n }\n if (title.toString().includes('Confirm Purchase')) {", "score": 0.8462140560150146 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " }, 10000)\n let handler = function (window: any) {\n sellHandler(data, bot, window, () => {\n clearTimeout(timeout)\n bot.removeAllListeners('windowOpen')\n })\n }\n bot.on('windowOpen', handler)\n bot.chat('/ah')\n}", "score": 0.8349764943122864 } ]
typescript
getWindowTitle(window) log('Claiming auction window: ' + title) if (title.toString().includes('Auction House')) {
import { ScoreBoard } from 'mineflayer' import { createBot } from 'mineflayer' import { createFastWindowClicker } from './fastWindowClick' import { addLoggerToClientWriteFunction, initLogger, log, printMcChatToConsole } from './logger' import { clickWindow, isCoflChatMessage, removeMinecraftColorCodes, sleep } from './utils' import { onWebsocketCreateAuction } from './sellHandler' import { tradePerson } from './tradeHandler' import { swapProfile } from './swapProfileHandler' import { flipHandler } from './flipHandler' import { registerIngameMessageHandler } from './ingameMessageHandler' import { MyBot, TextMessageData } from '../types/autobuy' import { getConfigProperty, initConfigHelper, updatePersistentConfigProperty } from './configHelper' import { getSessionId } from './coflSessionManager' import { sendWebhookInitialized } from './webhookHandler' import { setupConsoleInterface } from './consoleHandler' import { initAFKHandler, tryToTeleportToIsland } from './AFKHandler' const WebSocket = require('ws') var prompt = require('prompt-sync')() initConfigHelper() initLogger() const version = '1.5.0-af' let wss: WebSocket let ingameName = getConfigProperty('INGAME_NAME') if (!ingameName) { ingameName = prompt('Enter your ingame name: ') updatePersistentConfigProperty('INGAME_NAME', ingameName) } const bot: MyBot = createBot({ username: ingameName, auth: 'microsoft', logErrors: true, version: '1.17', host: 'mc.hypixel.net' }) bot.setMaxListeners(0) bot.state = 'gracePeriod' createFastWindowClicker(bot._client) if (getConfigProperty('LOG_PACKAGES')) { addLoggerToClientWriteFunction(bot._client) } bot.once('login', connectWebsocket) bot.once('spawn', async () => { await bot.waitForChunksToLoad() await sleep(2000) bot.chat('/play sb') bot.on('scoreboardTitleChanged', onScoreboardChanged) registerIngameMessageHandler(bot, wss) }) function connectWebsocket() { wss = new WebSocket(`wss://sky.coflnet.com/modsocket?player=${ingameName}&version=${version}&SId=${getSessionId(ingameName)}`) wss.onopen = function () { setupConsoleInterface(wss) sendWebhookInitialized() } wss.onmessage = onWebsocketMessage wss.onclose = function (e) { log('Connection closed. Reconnecting... ', 'warn') setTimeout(function () { connectWebsocket() }, 1000) } wss.onerror = function (err) { log('Connection error: ' + JSON.stringify(err), 'error') wss.close() } } async function onWebsocketMessage(msg) { let message = JSON.parse(msg.data) let data = JSON.parse(message.data) switch (message.type) { case 'flip': log(message, 'debug') flipHandler(bot, data) break case 'chatMessage':
for (let da of [...(data as TextMessageData[])]) {
let isCoflChat = isCoflChatMessage(da.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole(da.text) } } break case 'writeToChat': let isCoflChat = isCoflChatMessage(data.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole((data as TextMessageData).text) } break case 'swapProfile': log(message, 'debug') swapProfile(bot, data) break case 'createAuction': log(message, 'debug') onWebsocketCreateAuction(bot, data) break case 'trade': log(message, 'debug') tradePerson(bot, wss, data) break case 'tradeResponse': let tradeDisplay = (bot.currentWindow.slots[39].nbt.value as any).display.value.Name.value if (tradeDisplay.includes('Deal!') || tradeDisplay.includes('Warning!')) { await sleep(3400) } clickWindow(bot, 39) break case 'getInventory': log('Uploading inventory...') wss.send( JSON.stringify({ type: 'uploadInventory', data: JSON.stringify(bot.inventory) }) ) break case 'execute': log(message, 'debug') bot.chat(data) break case 'privacySettings': log(message, 'debug') data.chatRegex = new RegExp(data.chatRegex) bot.privacySettings = data break } } async function onScoreboardChanged() { if ( bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, '')).find(e => e.includes('Purse:') || e.includes('Piggy:')) ) { bot.removeListener('scoreboardTitleChanged', onScoreboardChanged) log('Joined SkyBlock') initAFKHandler(bot) setTimeout(() => { log('Waited for grace period to end. Flips can now be bought.') bot.state = null bot.removeAllListeners('scoreboardTitleChanged') wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) }, 5500) await sleep(2500) tryToTeleportToIsland(bot, 0) } }
src/BAF.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": "import { MyBot } from '../types/autobuy'\nimport { log, printMcChatToConsole } from './logger'\nimport { clickWindow, getWindowTitle } from './utils'\nimport { ChatMessage } from 'prismarine-chat'\nimport { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler'\nexport function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) {\n bot.on('message', (message: ChatMessage, type) => {\n let text = message.getText(null)\n if (type == 'chat') {\n printMcChatToConsole(message.toAnsi())", "score": 0.79096519947052 }, { "filename": "src/tradeHandler.ts", "retrieved_chunk": "import { MyBot, TradeData } from '../types/autobuy'\nimport { log } from './logger'\nimport { clickWindow, sleep } from './utils'\nexport async function tradePerson(bot: MyBot, websocket: WebSocket, data: TradeData) {\n let addedCoins = false\n let addedItems = false\n let trading = true\n while (trading) {\n bot.chat('/trade ' + data.target)\n bot.on('message', async msgE => {", "score": 0.7763153910636902 }, { "filename": "src/utils.ts", "retrieved_chunk": "export async function clickWindow(bot, slot: number) {\n return bot.clickWindow(slot, 0, 0)\n}\nexport async function sleep(ms: number): Promise<void> {\n return await new Promise(resolve => setTimeout(resolve, ms))\n}\nexport function getWindowTitle(window) {\n if (window.title) {\n let parsed = JSON.parse(window.title)\n return parsed.extra ? parsed['extra'][0]['text'] : parsed.translate", "score": 0.7548738121986389 }, { "filename": "src/swapProfileHandler.ts", "retrieved_chunk": "import { MyBot, SwapData } from '../types/autobuy'\nimport { log } from './logger'\nimport { clickWindow, getWindowTitle } from './utils'\nexport async function swapProfile(bot: MyBot, data: SwapData) {\n bot.setQuickBarSlot(8)\n bot.activateItem()\n bot.on('windowOpen', window => {\n let title = getWindowTitle(window)\n if (title == 'SkyBlock Menu') {\n clickWindow(bot, 48)", "score": 0.7516533136367798 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " }, 10000)\n let handler = function (window: any) {\n sellHandler(data, bot, window, () => {\n clearTimeout(timeout)\n bot.removeAllListeners('windowOpen')\n })\n }\n bot.on('windowOpen', handler)\n bot.chat('/ah')\n}", "score": 0.7515755891799927 } ]
typescript
for (let da of [...(data as TextMessageData[])]) {
import { MyBot } from '../types/autobuy' import { log, printMcChatToConsole } from './logger' import { clickWindow, getWindowTitle } from './utils' import { ChatMessage } from 'prismarine-chat' import { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler' export function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) { bot.on('message', (message: ChatMessage, type) => { let text = message.getText(null) if (type == 'chat') { printMcChatToConsole(message.toAnsi()) if (text.startsWith('You purchased')) { wss.send( JSON.stringify({ type: 'uploadTab', data: JSON.stringify(Object.keys(bot.players).map(playername => bot.players[playername].displayName.getText(null))) }) ) wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) claimPurchased(bot) sendWebhookItemPurchased(text.split(' purchased ')[1].split(' for ')[0], text.split(' for ')[1].split(' coins!')[0]) } if (text.startsWith('[Auction]') && text.includes('bought') && text.includes('for')) { log('New item sold') claimSoldItem(bot, text.split(' bought ')[1].split(' for ')[0]) sendWebhookItemSold( text.split(' bought ')[1].split(' for ')[0], text.split(' for ')[1].split(' coins')[0], text.split('[Auction] ')[1].split(' bought ')[0] ) }
if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) {
wss.send( JSON.stringify({ type: 'chatBatch', data: JSON.stringify([text]) }) ) } } }) } function claimPurchased(bot: MyBot) { if (bot.state) { log('Currently busy with something else (' + bot.state + ') -> not claiming purchased item') setTimeout(() => { claimPurchased(bot) }, 1000) return } bot.state = 'claiming' bot.chat('/ah') setTimeout(() => { log('Claiming of purchased auction failed. Removing lock') bot.state = null }, 5000) bot.on('windowOpen', window => { let title = getWindowTitle(window) log('Claiming auction window: ' + title) if (title.toString().includes('Auction House')) { clickWindow(bot, 13) } if (title.toString().includes('Your Bids')) { let slotToClick = -1 for (let i = 0; i < window.slots.length; i++) { const slot = window.slots[i] let name = (slot?.nbt as any)?.value?.display?.value?.Name?.value?.toString() if (slot?.type === 380 && name?.includes('Claim') && name?.includes('All')) { log('Found cauldron to claim all purchased auctions -> clicking index ' + i) clickWindow(bot, i) bot.removeAllListeners('windowOpen') bot.state = null return } let lore = (slot?.nbt as any)?.value?.display?.value?.Lore?.value?.value?.toString() if (lore?.includes('Status:') && lore?.includes('Sold!')) { log('Found claimable purchased auction. Gonna click index ' + i) log(JSON.stringify(slot)) slotToClick = i } } clickWindow(bot, slotToClick) } if (title.toString().includes('BIN Auction View')) { if (!window.slots[31]) { log('Weird error trying to claim purchased auction', 'warn') log(window.title) log(JSON.stringify(window.slots)) bot.removeAllListeners('windowOpen') bot.state = null return } if (window.slots[31].name.includes('gold_block')) { log('Claiming purchased auction...') clickWindow(bot, 31) } bot.removeAllListeners('windowOpen') bot.state = null } }) } async function claimSoldItem(bot: MyBot, itemName: string) { if (bot.state) { log('Currently busy with something else (' + bot.state + ') -> not claiming sold item') setTimeout(() => { claimSoldItem(bot, itemName) }, 1000) return } let timeout = setTimeout(() => { log('Seems something went wrong while claiming sold item. Removing lock') bot.state = null bot.removeAllListeners('windowOpen') }, 10000) bot.state = 'claiming' bot.chat('/ah') bot.on('windowOpen', window => { let title = getWindowTitle(window) if (title.toString().includes('Auction House')) { clickWindow(bot, 15) } if (title.toString().includes('Manage Auctions')) { log('Claiming sold auction...') let clickSlot for (let i = 0; i < window.slots.length; i++) { const item = window.slots[i] as any if (item?.nbt?.value?.display?.value?.Lore && JSON.stringify(item.nbt.value.display.value.Lore).includes('Sold for')) { clickSlot = item.slot } if (item && item.type === 380 && (item.nbt as any).value?.display?.value?.Name?.value?.toString().includes('Claim All')) { log(item) log('Found cauldron to claim all sold auctions -> clicking index ' + item.slot) clickWindow(bot, item.slot) clearTimeout(timeout) bot.removeAllListeners('windowOpen') bot.state = null return } } log('Clicking auction to claim, index: ' + clickSlot) log(JSON.stringify(window.slots[clickSlot])) clickWindow(bot, clickSlot) } if (title == 'BIN Auction View') { if (window.slots[31].name.includes('gold_block')) { log('Clicking slot 31, claiming purchased auction') clickWindow(bot, 31) } clearTimeout(timeout) bot.removeAllListeners('windowOpen') bot.state = null } }) }
src/ingameMessageHandler.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/BAF.ts", "retrieved_chunk": " onWebsocketCreateAuction(bot, data)\n break\n case 'trade':\n log(message, 'debug')\n tradePerson(bot, wss, data)\n break\n case 'tradeResponse':\n let tradeDisplay = (bot.currentWindow.slots[39].nbt.value as any).display.value.Name.value\n if (tradeDisplay.includes('Deal!') || tradeDisplay.includes('Warning!')) {\n await sleep(3400)", "score": 0.7176315784454346 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " priceLine = priceLine.split(': ')[1].split(' coins')[0]\n priceLine = priceLine.replace(/[,.]/g, '')\n }\n if (Number(priceLine) !== Math.floor(data.price)) {\n log('Price is not the one that should be there', 'error')\n log(data)\n log(sellWindow.slots[29])\n resetAndTakeOutItem()\n return\n }", "score": 0.7072288990020752 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " clickWindow(bot, clickSlot)\n }\n if (title == 'Create Auction') {\n clickWindow(bot, 48)\n }\n if (title == 'Create BIN Auction') {\n if (!setPrice && !durationSet) {\n if (!sellWindow.slots[13].nbt.value.display.value.Name.value.includes('Click an item in your inventory!')) {\n clickWindow(bot, 13)\n }", "score": 0.7066283226013184 }, { "filename": "src/consoleHandler.ts", "retrieved_chunk": " rl.on('line', input => {\n if (input?.startsWith('/cofl') && input?.split(' ').length >= 2) {\n let splits = input.split(' ')\n splits.shift() // remove /cofl\n let command = splits.shift()\n ws.send(\n JSON.stringify({\n type: command,\n data: `\"${splits.join(' ')}\"`\n })", "score": 0.6979424953460693 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " if (item && item.nbt.value.display.value.Name.value.includes('Create Auction')) {\n if (item && (item.nbt as any).value?.display?.value?.Lore?.value?.value?.toString().includes('You reached the maximum number')) {\n log('Maximum number of auctons reached -> cant sell')\n removeEventListenerCallback()\n bot.state = null\n return\n }\n clickSlot = item.slot\n }\n }", "score": 0.6924377679824829 } ]
typescript
if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) {
import { ScoreBoard } from 'mineflayer' import { createBot } from 'mineflayer' import { createFastWindowClicker } from './fastWindowClick' import { addLoggerToClientWriteFunction, initLogger, log, printMcChatToConsole } from './logger' import { clickWindow, isCoflChatMessage, removeMinecraftColorCodes, sleep } from './utils' import { onWebsocketCreateAuction } from './sellHandler' import { tradePerson } from './tradeHandler' import { swapProfile } from './swapProfileHandler' import { flipHandler } from './flipHandler' import { registerIngameMessageHandler } from './ingameMessageHandler' import { MyBot, TextMessageData } from '../types/autobuy' import { getConfigProperty, initConfigHelper, updatePersistentConfigProperty } from './configHelper' import { getSessionId } from './coflSessionManager' import { sendWebhookInitialized } from './webhookHandler' import { setupConsoleInterface } from './consoleHandler' import { initAFKHandler, tryToTeleportToIsland } from './AFKHandler' const WebSocket = require('ws') var prompt = require('prompt-sync')() initConfigHelper() initLogger() const version = '1.5.0-af' let wss: WebSocket let ingameName = getConfigProperty('INGAME_NAME') if (!ingameName) { ingameName = prompt('Enter your ingame name: ') updatePersistentConfigProperty('INGAME_NAME', ingameName) } const bot: MyBot = createBot({ username: ingameName, auth: 'microsoft', logErrors: true, version: '1.17', host: 'mc.hypixel.net' }) bot.setMaxListeners(0) bot.state = 'gracePeriod' createFastWindowClicker(bot._client) if (getConfigProperty('LOG_PACKAGES')) { addLoggerToClientWriteFunction(bot._client) } bot.once('login', connectWebsocket) bot.once('spawn', async () => { await bot.waitForChunksToLoad() await sleep(2000) bot.chat('/play sb') bot.on('scoreboardTitleChanged', onScoreboardChanged) registerIngameMessageHandler(bot, wss) }) function connectWebsocket() { wss = new WebSocket(`wss://sky.coflnet.com/modsocket?player=${ingameName}&version=${version}&SId=${getSessionId(ingameName)}`) wss.onopen = function () { setupConsoleInterface(wss) sendWebhookInitialized() } wss.onmessage = onWebsocketMessage wss.onclose = function (e) { log('Connection closed. Reconnecting... ', 'warn') setTimeout(function () { connectWebsocket() }, 1000) } wss.onerror = function (err) { log('Connection error: ' + JSON.stringify(err), 'error') wss.close() } } async function onWebsocketMessage(msg) { let message = JSON.parse(msg.data) let data = JSON.parse(message.data) switch (message.type) { case 'flip': log(message, 'debug') flipHandler(bot, data) break case 'chatMessage': for (let da of [...
(data as TextMessageData[])]) {
let isCoflChat = isCoflChatMessage(da.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole(da.text) } } break case 'writeToChat': let isCoflChat = isCoflChatMessage(data.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole((data as TextMessageData).text) } break case 'swapProfile': log(message, 'debug') swapProfile(bot, data) break case 'createAuction': log(message, 'debug') onWebsocketCreateAuction(bot, data) break case 'trade': log(message, 'debug') tradePerson(bot, wss, data) break case 'tradeResponse': let tradeDisplay = (bot.currentWindow.slots[39].nbt.value as any).display.value.Name.value if (tradeDisplay.includes('Deal!') || tradeDisplay.includes('Warning!')) { await sleep(3400) } clickWindow(bot, 39) break case 'getInventory': log('Uploading inventory...') wss.send( JSON.stringify({ type: 'uploadInventory', data: JSON.stringify(bot.inventory) }) ) break case 'execute': log(message, 'debug') bot.chat(data) break case 'privacySettings': log(message, 'debug') data.chatRegex = new RegExp(data.chatRegex) bot.privacySettings = data break } } async function onScoreboardChanged() { if ( bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, '')).find(e => e.includes('Purse:') || e.includes('Piggy:')) ) { bot.removeListener('scoreboardTitleChanged', onScoreboardChanged) log('Joined SkyBlock') initAFKHandler(bot) setTimeout(() => { log('Waited for grace period to end. Flips can now be bought.') bot.state = null bot.removeAllListeners('scoreboardTitleChanged') wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) }, 5500) await sleep(2500) tryToTeleportToIsland(bot, 0) } }
src/BAF.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": "import { MyBot } from '../types/autobuy'\nimport { log, printMcChatToConsole } from './logger'\nimport { clickWindow, getWindowTitle } from './utils'\nimport { ChatMessage } from 'prismarine-chat'\nimport { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler'\nexport function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) {\n bot.on('message', (message: ChatMessage, type) => {\n let text = message.getText(null)\n if (type == 'chat') {\n printMcChatToConsole(message.toAnsi())", "score": 0.7684134244918823 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " }, 10000)\n let handler = function (window: any) {\n sellHandler(data, bot, window, () => {\n clearTimeout(timeout)\n bot.removeAllListeners('windowOpen')\n })\n }\n bot.on('windowOpen', handler)\n bot.chat('/ah')\n}", "score": 0.7546757459640503 }, { "filename": "src/tradeHandler.ts", "retrieved_chunk": "import { MyBot, TradeData } from '../types/autobuy'\nimport { log } from './logger'\nimport { clickWindow, sleep } from './utils'\nexport async function tradePerson(bot: MyBot, websocket: WebSocket, data: TradeData) {\n let addedCoins = false\n let addedItems = false\n let trading = true\n while (trading) {\n bot.chat('/trade ' + data.target)\n bot.on('message', async msgE => {", "score": 0.7495238780975342 }, { "filename": "src/consoleHandler.ts", "retrieved_chunk": " rl.on('line', input => {\n if (input?.startsWith('/cofl') && input?.split(' ').length >= 2) {\n let splits = input.split(' ')\n splits.shift() // remove /cofl\n let command = splits.shift()\n ws.send(\n JSON.stringify({\n type: command,\n data: `\"${splits.join(' ')}\"`\n })", "score": 0.7432341575622559 }, { "filename": "src/consoleHandler.ts", "retrieved_chunk": " )\n } else {\n ws.send(\n JSON.stringify({\n type: 'chat',\n data: `\"${input}\"`\n })\n )\n }\n })", "score": 0.7397692203521729 } ]
typescript
(data as TextMessageData[])]) {
import { ScoreBoard } from 'mineflayer' import { createBot } from 'mineflayer' import { createFastWindowClicker } from './fastWindowClick' import { addLoggerToClientWriteFunction, initLogger, log, printMcChatToConsole } from './logger' import { clickWindow, isCoflChatMessage, removeMinecraftColorCodes, sleep } from './utils' import { onWebsocketCreateAuction } from './sellHandler' import { tradePerson } from './tradeHandler' import { swapProfile } from './swapProfileHandler' import { flipHandler } from './flipHandler' import { registerIngameMessageHandler } from './ingameMessageHandler' import { MyBot, TextMessageData } from '../types/autobuy' import { getConfigProperty, initConfigHelper, updatePersistentConfigProperty } from './configHelper' import { getSessionId } from './coflSessionManager' import { sendWebhookInitialized } from './webhookHandler' import { setupConsoleInterface } from './consoleHandler' import { initAFKHandler, tryToTeleportToIsland } from './AFKHandler' const WebSocket = require('ws') var prompt = require('prompt-sync')() initConfigHelper() initLogger() const version = '1.5.0-af' let wss: WebSocket let ingameName = getConfigProperty('INGAME_NAME') if (!ingameName) { ingameName = prompt('Enter your ingame name: ') updatePersistentConfigProperty('INGAME_NAME', ingameName) } const bot: MyBot = createBot({ username: ingameName, auth: 'microsoft', logErrors: true, version: '1.17', host: 'mc.hypixel.net' }) bot.setMaxListeners(0) bot.state = 'gracePeriod' createFastWindowClicker(bot._client) if (getConfigProperty('LOG_PACKAGES')) { addLoggerToClientWriteFunction(bot._client) } bot.once('login', connectWebsocket) bot.once('spawn', async () => { await bot.waitForChunksToLoad() await sleep(2000) bot.chat('/play sb') bot.on('scoreboardTitleChanged', onScoreboardChanged) registerIngameMessageHandler(bot, wss) }) function connectWebsocket() {
wss = new WebSocket(`wss://sky.coflnet.com/modsocket?player=${ingameName}&version=${version}&SId=${getSessionId(ingameName)}`) wss.onopen = function () {
setupConsoleInterface(wss) sendWebhookInitialized() } wss.onmessage = onWebsocketMessage wss.onclose = function (e) { log('Connection closed. Reconnecting... ', 'warn') setTimeout(function () { connectWebsocket() }, 1000) } wss.onerror = function (err) { log('Connection error: ' + JSON.stringify(err), 'error') wss.close() } } async function onWebsocketMessage(msg) { let message = JSON.parse(msg.data) let data = JSON.parse(message.data) switch (message.type) { case 'flip': log(message, 'debug') flipHandler(bot, data) break case 'chatMessage': for (let da of [...(data as TextMessageData[])]) { let isCoflChat = isCoflChatMessage(da.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole(da.text) } } break case 'writeToChat': let isCoflChat = isCoflChatMessage(data.text) if (!isCoflChat) { log(message, 'debug') } if (getConfigProperty('USE_COFL_CHAT') || !isCoflChat) { printMcChatToConsole((data as TextMessageData).text) } break case 'swapProfile': log(message, 'debug') swapProfile(bot, data) break case 'createAuction': log(message, 'debug') onWebsocketCreateAuction(bot, data) break case 'trade': log(message, 'debug') tradePerson(bot, wss, data) break case 'tradeResponse': let tradeDisplay = (bot.currentWindow.slots[39].nbt.value as any).display.value.Name.value if (tradeDisplay.includes('Deal!') || tradeDisplay.includes('Warning!')) { await sleep(3400) } clickWindow(bot, 39) break case 'getInventory': log('Uploading inventory...') wss.send( JSON.stringify({ type: 'uploadInventory', data: JSON.stringify(bot.inventory) }) ) break case 'execute': log(message, 'debug') bot.chat(data) break case 'privacySettings': log(message, 'debug') data.chatRegex = new RegExp(data.chatRegex) bot.privacySettings = data break } } async function onScoreboardChanged() { if ( bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, '')).find(e => e.includes('Purse:') || e.includes('Piggy:')) ) { bot.removeListener('scoreboardTitleChanged', onScoreboardChanged) log('Joined SkyBlock') initAFKHandler(bot) setTimeout(() => { log('Waited for grace period to end. Flips can now be bought.') bot.state = null bot.removeAllListeners('scoreboardTitleChanged') wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) }, 5500) await sleep(2500) tryToTeleportToIsland(bot, 0) } }
src/BAF.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/sellHandler.ts", "retrieved_chunk": " bot.state = null\n printMcChatToConsole(`§f[§4BAF§f]: §fItem listed: ${data.itemName} §ffor ${numberWithThousandsSeparators(data.price)} coins`)\n sendWebhookItemListed(data.itemName, numberWithThousandsSeparators(data.price), data.duration)\n bot.closeWindow(sellWindow)\n }\n}\nasync function setAuctionDuration(bot: MyBot, time: number) {\n log('setAuctionDuration function')\n return new Promise<void>(resolve => {\n bot._client.once('open_sign_entity', ({ location }) => {", "score": 0.7144042253494263 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " }, 10000)\n let handler = function (window: any) {\n sellHandler(data, bot, window, () => {\n clearTimeout(timeout)\n bot.removeAllListeners('windowOpen')\n })\n }\n bot.on('windowOpen', handler)\n bot.chat('/ah')\n}", "score": 0.695658802986145 }, { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": " if (text.startsWith('You purchased')) {\n wss.send(\n JSON.stringify({\n type: 'uploadTab',\n data: JSON.stringify(Object.keys(bot.players).map(playername => bot.players[playername].displayName.getText(null)))\n })\n )\n wss.send(\n JSON.stringify({\n type: 'uploadScoreboard',", "score": 0.685813307762146 }, { "filename": "src/AFKHandler.ts", "retrieved_chunk": " if (\n !bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, '')).find(e => e.includes('Purse:') || e.includes('Piggy:'))\n ) {\n await sleep(delayBeforeTeleport)\n log(`Bot seems to be in lobby (Sidebar title = ${bot.scoreboard.sidebar.title}). Sending \"/play sb\"`)\n printMcChatToConsole('§f[§4BAF§f]: §fYou seem to be in the lobby.')\n printMcChatToConsole('§f[§4BAF§f]: §fWarping back into skyblock...')\n bot.chat('/play sb')\n return true\n }", "score": 0.6855058670043945 }, { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": "import { MyBot } from '../types/autobuy'\nimport { log, printMcChatToConsole } from './logger'\nimport { clickWindow, getWindowTitle } from './utils'\nimport { ChatMessage } from 'prismarine-chat'\nimport { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler'\nexport function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) {\n bot.on('message', (message: ChatMessage, type) => {\n let text = message.getText(null)\n if (type == 'chat') {\n printMcChatToConsole(message.toAnsi())", "score": 0.6713492274284363 } ]
typescript
wss = new WebSocket(`wss://sky.coflnet.com/modsocket?player=${ingameName}&version=${version}&SId=${getSessionId(ingameName)}`) wss.onopen = function () {
import { MyBot } from '../types/autobuy' import { log, printMcChatToConsole } from './logger' import { clickWindow, getWindowTitle } from './utils' import { ChatMessage } from 'prismarine-chat' import { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler' export function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) { bot.on('message', (message: ChatMessage, type) => { let text = message.getText(null) if (type == 'chat') { printMcChatToConsole(message.toAnsi()) if (text.startsWith('You purchased')) { wss.send( JSON.stringify({ type: 'uploadTab', data: JSON.stringify(Object.keys(bot.players).map(playername => bot.players[playername].displayName.getText(null))) }) ) wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) claimPurchased(bot) sendWebhookItemPurchased(text.split(' purchased ')[1].split(' for ')[0], text.split(' for ')[1].split(' coins!')[0]) } if (text.startsWith('[Auction]') && text.includes('bought') && text.includes('for')) { log('New item sold') claimSoldItem(bot, text.split(' bought ')[1].split(' for ')[0]) sendWebhookItemSold( text.split(' bought ')[1].split(' for ')[0], text.split(' for ')[1].split(' coins')[0], text.split('[Auction] ')[1].split(' bought ')[0] ) } if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) { wss.send( JSON.stringify({ type: 'chatBatch', data: JSON.stringify([text]) }) ) } } }) } function claimPurchased(bot: MyBot) { if (bot.state) { log('Currently busy with something else (' + bot.state + ') -> not claiming purchased item') setTimeout(() => { claimPurchased(bot) }, 1000) return } bot.state = 'claiming' bot.chat('/ah') setTimeout(() => { log('Claiming of purchased auction failed. Removing lock') bot.state = null }, 5000) bot.on('windowOpen', window => { let title = getWindowTitle(window) log('Claiming auction window: ' + title) if (title.toString().includes('Auction House')) { clickWindow(bot, 13) } if (title.toString().includes('Your Bids')) { let slotToClick = -1 for (let i = 0; i < window.slots.length; i++) { const slot = window.slots[i] let name = (slot?.nbt as any)?.value?.display?.value?.Name?.value?.toString() if (slot?.type === 380 && name?.includes('Claim') && name?.includes('All')) { log('Found cauldron to claim all purchased auctions -> clicking index ' + i) clickWindow(bot, i)
bot.removeAllListeners('windowOpen') bot.state = null return }
let lore = (slot?.nbt as any)?.value?.display?.value?.Lore?.value?.value?.toString() if (lore?.includes('Status:') && lore?.includes('Sold!')) { log('Found claimable purchased auction. Gonna click index ' + i) log(JSON.stringify(slot)) slotToClick = i } } clickWindow(bot, slotToClick) } if (title.toString().includes('BIN Auction View')) { if (!window.slots[31]) { log('Weird error trying to claim purchased auction', 'warn') log(window.title) log(JSON.stringify(window.slots)) bot.removeAllListeners('windowOpen') bot.state = null return } if (window.slots[31].name.includes('gold_block')) { log('Claiming purchased auction...') clickWindow(bot, 31) } bot.removeAllListeners('windowOpen') bot.state = null } }) } async function claimSoldItem(bot: MyBot, itemName: string) { if (bot.state) { log('Currently busy with something else (' + bot.state + ') -> not claiming sold item') setTimeout(() => { claimSoldItem(bot, itemName) }, 1000) return } let timeout = setTimeout(() => { log('Seems something went wrong while claiming sold item. Removing lock') bot.state = null bot.removeAllListeners('windowOpen') }, 10000) bot.state = 'claiming' bot.chat('/ah') bot.on('windowOpen', window => { let title = getWindowTitle(window) if (title.toString().includes('Auction House')) { clickWindow(bot, 15) } if (title.toString().includes('Manage Auctions')) { log('Claiming sold auction...') let clickSlot for (let i = 0; i < window.slots.length; i++) { const item = window.slots[i] as any if (item?.nbt?.value?.display?.value?.Lore && JSON.stringify(item.nbt.value.display.value.Lore).includes('Sold for')) { clickSlot = item.slot } if (item && item.type === 380 && (item.nbt as any).value?.display?.value?.Name?.value?.toString().includes('Claim All')) { log(item) log('Found cauldron to claim all sold auctions -> clicking index ' + item.slot) clickWindow(bot, item.slot) clearTimeout(timeout) bot.removeAllListeners('windowOpen') bot.state = null return } } log('Clicking auction to claim, index: ' + clickSlot) log(JSON.stringify(window.slots[clickSlot])) clickWindow(bot, clickSlot) } if (title == 'BIN Auction View') { if (window.slots[31].name.includes('gold_block')) { log('Clicking slot 31, claiming purchased auction') clickWindow(bot, 31) } clearTimeout(timeout) bot.removeAllListeners('windowOpen') bot.state = null } }) }
src/ingameMessageHandler.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/swapProfileHandler.ts", "retrieved_chunk": " }\n if (title == 'Profile Management') {\n let clickSlot\n window.slots.forEach(item => {\n if (item && (item.nbt.value as any).display.value.Name.value.includes((data as SwapData).profile)) clickSlot = item.slot\n })\n log('Clickslot is ' + clickSlot)\n clickWindow(bot, clickSlot)\n }\n if (title.includes('Profile:')) {", "score": 0.8541756868362427 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": "async function sellHandler(data: SellData, bot: MyBot, sellWindow, removeEventListenerCallback: Function) {\n let title = getWindowTitle(sellWindow)\n log(title)\n if (title.toString().includes('Auction House')) {\n clickWindow(bot, 15)\n }\n if (title == 'Manage Auctions') {\n let clickSlot\n for (let i = 0; i < sellWindow.slots.length; i++) {\n const item = sellWindow.slots[i]", "score": 0.8412889838218689 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " if (data.id !== id && data.id !== uuid) {\n bot.state = null\n removeEventListenerCallback()\n log('Item at index ' + itemSlot + '\" does not match item that is supposed to be sold: \"' + data.id + '\" -> dont sell', 'warn')\n log(JSON.stringify(sellWindow.slots[itemSlot]))\n return\n }\n clickWindow(bot, itemSlot)\n bot._client.once('open_sign_entity', ({ location }) => {\n let price = (data as SellData).price", "score": 0.8381752967834473 }, { "filename": "src/tradeHandler.ts", "retrieved_chunk": " } else if (msg.startsWith('You have sent a trade request to ')) {\n log('successfully sent trade, waiting for them to accept')\n bot.on('windowOpen', async window => {\n trading = false\n log('Trade window opened')\n if (!addedItems) {\n for (let slot of data.slots) {\n slot += 44\n clickWindow(bot, slot)\n log('Clicked slot ' + slot)", "score": 0.8348644971847534 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " // calculate item slot, by calculating the slot index without the chest\n let itemSlot = data.slot - bot.inventory.inventoryStart + sellWindow.inventoryStart\n if (!sellWindow.slots[itemSlot]) {\n bot.state = null\n removeEventListenerCallback()\n log('No item at index ' + itemSlot + ' found -> probably already sold', 'warn')\n return\n }\n let id = sellWindow.slots[itemSlot]?.nbt?.value?.ExtraAttributes?.value?.id?.value\n let uuid = sellWindow.slots[itemSlot]?.nbt?.value?.ExtraAttributes?.value?.uuid?.value", "score": 0.8339189887046814 } ]
typescript
bot.removeAllListeners('windowOpen') bot.state = null return }
import { MyBot } from '../types/autobuy' import { log, printMcChatToConsole } from './logger' import { clickWindow, getWindowTitle } from './utils' import { ChatMessage } from 'prismarine-chat' import { sendWebhookItemPurchased, sendWebhookItemSold } from './webhookHandler' export function registerIngameMessageHandler(bot: MyBot, wss: WebSocket) { bot.on('message', (message: ChatMessage, type) => { let text = message.getText(null) if (type == 'chat') { printMcChatToConsole(message.toAnsi()) if (text.startsWith('You purchased')) { wss.send( JSON.stringify({ type: 'uploadTab', data: JSON.stringify(Object.keys(bot.players).map(playername => bot.players[playername].displayName.getText(null))) }) ) wss.send( JSON.stringify({ type: 'uploadScoreboard', data: JSON.stringify(bot.scoreboard.sidebar.items.map(item => item.displayName.getText(null).replace(item.name, ''))) }) ) claimPurchased(bot) sendWebhookItemPurchased(text.split(' purchased ')[1].split(' for ')[0], text.split(' for ')[1].split(' coins!')[0]) } if (text.startsWith('[Auction]') && text.includes('bought') && text.includes('for')) { log('New item sold') claimSoldItem(bot, text.split(' bought ')[1].split(' for ')[0]) sendWebhookItemSold( text.split(' bought ')[1].split(' for ')[0], text.split(' for ')[1].split(' coins')[0], text.split('[Auction] ')[1].split(' bought ')[0] ) } if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) { wss.send( JSON.stringify({ type: 'chatBatch', data: JSON.stringify([text]) }) ) } } }) } function claimPurchased(bot: MyBot) { if (bot.state) { log('Currently busy with something else (' + bot.state + ') -> not claiming purchased item') setTimeout(() => { claimPurchased(bot) }, 1000) return } bot.state = 'claiming'
bot.chat('/ah') setTimeout(() => {
log('Claiming of purchased auction failed. Removing lock') bot.state = null }, 5000) bot.on('windowOpen', window => { let title = getWindowTitle(window) log('Claiming auction window: ' + title) if (title.toString().includes('Auction House')) { clickWindow(bot, 13) } if (title.toString().includes('Your Bids')) { let slotToClick = -1 for (let i = 0; i < window.slots.length; i++) { const slot = window.slots[i] let name = (slot?.nbt as any)?.value?.display?.value?.Name?.value?.toString() if (slot?.type === 380 && name?.includes('Claim') && name?.includes('All')) { log('Found cauldron to claim all purchased auctions -> clicking index ' + i) clickWindow(bot, i) bot.removeAllListeners('windowOpen') bot.state = null return } let lore = (slot?.nbt as any)?.value?.display?.value?.Lore?.value?.value?.toString() if (lore?.includes('Status:') && lore?.includes('Sold!')) { log('Found claimable purchased auction. Gonna click index ' + i) log(JSON.stringify(slot)) slotToClick = i } } clickWindow(bot, slotToClick) } if (title.toString().includes('BIN Auction View')) { if (!window.slots[31]) { log('Weird error trying to claim purchased auction', 'warn') log(window.title) log(JSON.stringify(window.slots)) bot.removeAllListeners('windowOpen') bot.state = null return } if (window.slots[31].name.includes('gold_block')) { log('Claiming purchased auction...') clickWindow(bot, 31) } bot.removeAllListeners('windowOpen') bot.state = null } }) } async function claimSoldItem(bot: MyBot, itemName: string) { if (bot.state) { log('Currently busy with something else (' + bot.state + ') -> not claiming sold item') setTimeout(() => { claimSoldItem(bot, itemName) }, 1000) return } let timeout = setTimeout(() => { log('Seems something went wrong while claiming sold item. Removing lock') bot.state = null bot.removeAllListeners('windowOpen') }, 10000) bot.state = 'claiming' bot.chat('/ah') bot.on('windowOpen', window => { let title = getWindowTitle(window) if (title.toString().includes('Auction House')) { clickWindow(bot, 15) } if (title.toString().includes('Manage Auctions')) { log('Claiming sold auction...') let clickSlot for (let i = 0; i < window.slots.length; i++) { const item = window.slots[i] as any if (item?.nbt?.value?.display?.value?.Lore && JSON.stringify(item.nbt.value.display.value.Lore).includes('Sold for')) { clickSlot = item.slot } if (item && item.type === 380 && (item.nbt as any).value?.display?.value?.Name?.value?.toString().includes('Claim All')) { log(item) log('Found cauldron to claim all sold auctions -> clicking index ' + item.slot) clickWindow(bot, item.slot) clearTimeout(timeout) bot.removeAllListeners('windowOpen') bot.state = null return } } log('Clicking auction to claim, index: ' + clickSlot) log(JSON.stringify(window.slots[clickSlot])) clickWindow(bot, clickSlot) } if (title == 'BIN Auction View') { if (window.slots[31].name.includes('gold_block')) { log('Clicking slot 31, claiming purchased auction') clickWindow(bot, 31) } clearTimeout(timeout) bot.removeAllListeners('windowOpen') bot.state = null } }) }
src/ingameMessageHandler.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/sellHandler.ts", "retrieved_chunk": " bot.state = 'selling'\n log('Selling item...')\n log(data)\n sellItem(data, bot)\n}\nasync function sellItem(data: SellData, bot: MyBot) {\n let timeout = setTimeout(() => {\n log('Seems something went wrong while selling. Removing lock', 'warn')\n bot.state = null\n bot.removeAllListeners('windowOpen')", "score": 0.8546534180641174 }, { "filename": "src/flipHandler.ts", "retrieved_chunk": " }, 1100)\n return\n }\n bot.state = 'purchasing'\n let timeout = setTimeout(() => {\n if (bot.state === 'purchasing') {\n log(\"Resetting 'bot.state === purchasing' lock\")\n bot.state = null\n bot.removeAllListeners('windowOpen')\n }", "score": 0.8481155633926392 }, { "filename": "src/flipHandler.ts", "retrieved_chunk": " )\n if (getConfigProperty('USE_WINDOW_SKIPS')) {\n useWindowSkipPurchase(flip, isBed)\n // clear timeout after 1sec, so there are no weird overlaps that mess up the windowIds\n setTimeout(() => {\n bot.state = null\n clearTimeout(timeout)\n }, 2500)\n } else {\n useRegularPurchase(bot)", "score": 0.8402590751647949 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " if (data.id !== id && data.id !== uuid) {\n bot.state = null\n removeEventListenerCallback()\n log('Item at index ' + itemSlot + '\" does not match item that is supposed to be sold: \"' + data.id + '\" -> dont sell', 'warn')\n log(JSON.stringify(sellWindow.slots[itemSlot]))\n return\n }\n clickWindow(bot, itemSlot)\n bot._client.once('open_sign_entity', ({ location }) => {\n let price = (data as SellData).price", "score": 0.840179443359375 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " if (retryCount > 3) {\n retryCount = 0\n return\n }\n setTimeout(() => {\n retryCount++\n onWebsocketCreateAuction(bot, data)\n }, 1000)\n return\n }", "score": 0.8353183269500732 } ]
typescript
bot.chat('/ah') setTimeout(() => {
import { MyBot, TradeData } from '../types/autobuy' import { log } from './logger' import { clickWindow, sleep } from './utils' export async function tradePerson(bot: MyBot, websocket: WebSocket, data: TradeData) { let addedCoins = false let addedItems = false let trading = true while (trading) { bot.chat('/trade ' + data.target) bot.on('message', async msgE => { let msg = msgE.getText(null) if (msg == 'You cannot trade while the server is lagging!') { bot.chat('The server is lagging, give it a second') await sleep(5000) } else if (msg.startsWith('Cannot find player named')) { log('Player is not avaliable to trade with, please rerequest when they are capable of trading') trading = false return } else if (msg == 'You are too far away to trade with that player!') { bot.chat('Hey ' + data.target + ' come here so we can trade!') } else if (msg.startsWith('You have sent a trade request to ')) { log('successfully sent trade, waiting for them to accept') bot.on('windowOpen', async window => { trading = false log('Trade window opened') if (!addedItems) { for (let slot of data.slots) { slot += 44 clickWindow(bot, slot) log('Clicked slot ' + slot) } log('Added all items') }
if (data.coins > 0 && !addedCoins) {
bot._client.once('open_sign_entity', ({ location }) => { let price = data.coins log('New sign entity') log('price to set ' + Math.floor(price).toString()) bot._client.write('update_sign', { location: { x: location.z, y: location.y, z: location.z }, text1: `\"${Math.floor(price).toString()}\"`, text2: '{"italic":false,"extra":["^^^^^^^^^^^^^^^"],"text":""}', text3: '{"italic":false,"extra":["Your auction"],"text":""}', text4: '{"italic":false,"extra":["starting bid"],"text":""}' }) addedCoins = true }) clickWindow(bot, 36) } if (!(data.coins > 0) || addedCoins) { websocket.send(JSON.stringify({ type: 'affirmFlip', data: [JSON.stringify(window.slots)] })) } }) } }) await sleep(5000) } }
src/tradeHandler.ts
Hannesimo-auto-flipper-04dcf73
[ { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": " bot.on('windowOpen', window => {\n let title = getWindowTitle(window)\n log('Claiming auction window: ' + title)\n if (title.toString().includes('Auction House')) {\n clickWindow(bot, 13)\n }\n if (title.toString().includes('Your Bids')) {\n let slotToClick = -1\n for (let i = 0; i < window.slots.length; i++) {\n const slot = window.slots[i]", "score": 0.8517016172409058 }, { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": " bot.on('windowOpen', window => {\n let title = getWindowTitle(window)\n if (title.toString().includes('Auction House')) {\n clickWindow(bot, 15)\n }\n if (title.toString().includes('Manage Auctions')) {\n log('Claiming sold auction...')\n let clickSlot\n for (let i = 0; i < window.slots.length; i++) {\n const item = window.slots[i] as any", "score": 0.8435781598091125 }, { "filename": "src/ingameMessageHandler.ts", "retrieved_chunk": " log('Found claimable purchased auction. Gonna click index ' + i)\n log(JSON.stringify(slot))\n slotToClick = i\n }\n }\n clickWindow(bot, slotToClick)\n }\n if (title.toString().includes('BIN Auction View')) {\n if (!window.slots[31]) {\n log('Weird error trying to claim purchased auction', 'warn')", "score": 0.840374231338501 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": " if (data.id !== id && data.id !== uuid) {\n bot.state = null\n removeEventListenerCallback()\n log('Item at index ' + itemSlot + '\" does not match item that is supposed to be sold: \"' + data.id + '\" -> dont sell', 'warn')\n log(JSON.stringify(sellWindow.slots[itemSlot]))\n return\n }\n clickWindow(bot, itemSlot)\n bot._client.once('open_sign_entity', ({ location }) => {\n let price = (data as SellData).price", "score": 0.8305754661560059 }, { "filename": "src/sellHandler.ts", "retrieved_chunk": "async function sellHandler(data: SellData, bot: MyBot, sellWindow, removeEventListenerCallback: Function) {\n let title = getWindowTitle(sellWindow)\n log(title)\n if (title.toString().includes('Auction House')) {\n clickWindow(bot, 15)\n }\n if (title == 'Manage Auctions') {\n let clickSlot\n for (let i = 0; i < sellWindow.slots.length; i++) {\n const item = sellWindow.slots[i]", "score": 0.8230242133140564 } ]
typescript
if (data.coins > 0 && !addedCoins) {
import { BattleStats } from "../../value_objects/BattleStats"; import { Item } from "../item/Item"; import { League } from "../league/League"; import { Pokemon } from "../pokemon/Pokemon"; export class Trainer { private _id: string; private _name: string; private _city: string; private _age: number; private _level: number; private _pokemons: Pokemon[]; private _items: Item[]; private _league: League | null; constructor(props: { id: string; name: string; city: string; age: number; level: number; pokemons: Pokemon[]; items: Item[]; league: League | null; }) { this._id = props.id; this._name = props.name; this._city = props.city; this._age = props.age; this._level = props.level; this._pokemons = props.pokemons; this._items = props.items; this._league = props.league; } // Methods addPokemon(pokemon: Pokemon) { this._pokemons.push(pokemon); } removePokemon(pokemon: Pokemon): void { this._pokemons = this._pokemons.filter((p) => p.equals(pokemon)); } addItem(item: Item) { this._items.push(item); } removeItem(item: Item): void { this._items = this._items.filter((i) => i.equals(item)); } applyItem(item: Item, pokemon: Pokemon): void { pokemon.life += item.increaseLife; const newStats = new BattleStats({ attack: pokemon.stats.attack + item.
increaseAttack, defense: pokemon.stats.defense + item.increaseDefense, speed: pokemon.stats.speed + item.increaseSpeed, });
pokemon.stats = newStats; } // Getters and setters get id(): string { return this._id; } set id(id: string) { this._id = id; } get name(): string { return this._name; } set name(name: string) { this._name = name; } get city(): string { return this._city; } set city(city: string) { this._city = city; } get age(): number { return this._age; } set age(age: number) { this._age = age; } get level(): number { return this._level; } set level(level: number) { this._level = level; } get pokemons() { return this._pokemons; } set pokemons(pokemon: Pokemon[]) { this._pokemons = pokemon; } get items() { return this._items; } set items(items: Item[]) { this._items = items; } get league() { return this._league; } set league(league: League | null) { this._league = league; } }
src/app/entities/trainer/Trainer.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": " increaseLife: number;\n increaseAttack: number;\n increaseDefense: number;\n increaseSpeed: number;\n }) {\n this._id = props.id;\n this._name = props.name;\n this._increaseLife = props.increaseLife;\n this._increaseAttack = props.increaseAttack;\n this._increaseDefense = props.increaseDefense;", "score": 0.7753638029098511 }, { "filename": "src/app/entities/pokemon/Pokemon.ts", "retrieved_chunk": " }\n // Predicates\n isAwake(): boolean {\n return this.life > 0;\n }\n // Actions\n attack(target: Pokemon): void {\n const damage = this._stats.attack - target.stats.defense;\n if (damage > 0) {\n target.life -= damage;", "score": 0.7567772269248962 }, { "filename": "src/app/use-cases/pokemon/AddPokemonUseCase.ts", "retrieved_chunk": " life: life,\n type: type,\n stats: stats,\n moves: moves,\n });\n const trainerPokemons = await this.pokemonRepository.findByTrainerId(\n pokemon.trainerID\n );\n if (trainerPokemons.length >= 3) {\n throw new Error(\"Trainer already has 3 pokemons\");", "score": 0.7450456619262695 }, { "filename": "src/app/entities/pokemon/Pokemon.ts", "retrieved_chunk": " }\n set moves(moves: PokemonMove[]) {\n this._moves = moves;\n }\n // Equals\n equals(other: Pokemon): boolean {\n return (\n this.id === other.id &&\n this.name === other.name &&\n this.level === other.level &&", "score": 0.7415890693664551 }, { "filename": "src/app/value_objects/BattleStats.ts", "retrieved_chunk": "export class BattleStats {\n private _attack: number;\n private _defense: number;\n private _speed: number;\n constructor(props: { attack: number; defense: number; speed: number }) {\n this._attack = props.attack;\n this._defense = props.defense;\n this._speed = props.speed;\n }\n get attack() {", "score": 0.7320375442504883 } ]
typescript
increaseAttack, defense: pokemon.stats.defense + item.increaseDefense, speed: pokemon.stats.speed + item.increaseSpeed, });
import { isEqual } from "lodash"; import { PokemonMove } from "../../value_objects/PokemonMove"; import { BattleStats } from "../../value_objects/BattleStats"; export class Pokemon { private _id: string; private _name: string; private _level: number; private _life: number; private _type: string[]; private _trainerID: string; private _stats: BattleStats; private _moves: PokemonMove[]; constructor(props: { id: string; name: string; level: number; life: number; type: string[]; trainerID: string; stats: BattleStats; moves: PokemonMove[]; }) { this._id = props.id; this._name = props.name; this._level = props.level; this._life = props.life; this._type = props.type; this._trainerID = props.trainerID; this._stats = props.stats; this._moves = props.moves; } // Predicates isAwake(): boolean { return this.life > 0; } // Actions attack(target: Pokemon): void { const damage
= this._stats.attack - target.stats.defense;
if (damage > 0) { target.life -= damage; } if (target.life < 0) { target.life = 0; } } // Getters and setters get id(): string { return this._id; } set id(id: string) { this._id = id; } get name(): string { return this._name; } set name(name: string) { this._name = name; } get level(): number { return this._level; } set level(level: number) { this._level = level; } get life(): number { return this._life; } set life(life: number) { this._life = life; } get type(): string[] { return this._type; } set type(type: string[]) { this._type = type; } get trainerID(): string { return this._trainerID; } set trainerID(trainerID: string) { this._trainerID = trainerID; } get stats(): BattleStats { return this._stats; } set stats(stats: BattleStats) { this._stats = stats; } get moves(): PokemonMove[] { return this._moves; } set moves(moves: PokemonMove[]) { this._moves = moves; } // Equals equals(other: Pokemon): boolean { return ( this.id === other.id && this.name === other.name && this.level === other.level && this.trainerID === other.trainerID && this.stats.equals(other.stats) && isEqual(this.type, other.type) && isEqual(this.moves, other.moves) ); } }
src/app/entities/pokemon/Pokemon.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/value_objects/BattleStats.ts", "retrieved_chunk": " return this._attack;\n }\n get defense() {\n return this._defense;\n }\n get speed() {\n return this._speed;\n }\n equals(other: BattleStats): boolean {\n return (", "score": 0.853299617767334 }, { "filename": "src/app/entities/trainer/Trainer.ts", "retrieved_chunk": " speed: pokemon.stats.speed + item.increaseSpeed,\n });\n pokemon.stats = newStats;\n }\n // Getters and setters\n get id(): string {\n return this._id;\n }\n set id(id: string) {\n this._id = id;", "score": 0.8338243365287781 }, { "filename": "src/app/entities/league/League.ts", "retrieved_chunk": " this._startedAt = new Date();\n }\n finish(): void {\n this._finishedAt = new Date();\n }\n isFinished(): boolean {\n return this._finishedAt !== null;\n }\n equals(battle: League): boolean {\n return this._id === battle.id;", "score": 0.8293249607086182 }, { "filename": "src/app/entities/trainer/Trainer.ts", "retrieved_chunk": " this._items.push(item);\n }\n removeItem(item: Item): void {\n this._items = this._items.filter((i) => i.equals(item));\n }\n applyItem(item: Item, pokemon: Pokemon): void {\n pokemon.life += item.increaseLife;\n const newStats = new BattleStats({\n attack: pokemon.stats.attack + item.increaseAttack,\n defense: pokemon.stats.defense + item.increaseDefense,", "score": 0.8110652565956116 }, { "filename": "src/app/use-cases/pokemon/AddPokemonUseCase.ts", "retrieved_chunk": " life: life,\n type: type,\n stats: stats,\n moves: moves,\n });\n const trainerPokemons = await this.pokemonRepository.findByTrainerId(\n pokemon.trainerID\n );\n if (trainerPokemons.length >= 3) {\n throw new Error(\"Trainer already has 3 pokemons\");", "score": 0.8010963201522827 } ]
typescript
= this._stats.attack - target.stats.defense;