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/Array.ts",
"retrieved_chunk": " * @example\n * pipe(\n * [32, null, 55, undefined, 89], // (number | null | undefined)[]\n * Array.chooseR(x => pipe(\n * x, // number | null | undefined\n * Option.ofNullish, // Option<number>\n * Option.map(String), // Option<string>\n * Result.ofOption(() => \"err\") // Result<string, string>\n * )) // string[]\n * ) // => [\"32\", \"55\", \"89\"]",
"score": 22.29755769268663
},
{
"filename": "src/Array.ts",
"retrieved_chunk": " * @example\n * pipe(\n * [32, null, 55, undefined, 89], // (number | null | undefined)[]\n * Array.choose(x => pipe(\n * x, // number | null | undefined\n * Option.ofNullish, // Option<number>\n * Option.map(String) // Option<string>\n * )) // string[]\n * ) // => [\"32\", \"55\", \"89\"]\n */",
"score": 17.201516116921255
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " * value. Pass a matcher function with cases for `ok` and `err` that\n * can either be lambdas or raw values.\n *\n * @group Pattern Matching\n *\n * @example\n * ```\n * pipe(\n * Result.err(\"failure\"),\n * Result.match({",
"score": 15.217992748603344
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " * @group Mapping\n *\n * @example\n * pipe(\n * Result.ok(\"a\"),\n * Result.bind(s =>\n * s === \"a\" ? Result.ok(\"got an a!\") : Result.err(\"not an a\")\n * ),\n * Result.defaultValue(\"\")\n * ) // => \"got an a!\"",
"score": 14.517045940775231
},
{
"filename": "src/AsyncResult.ts",
"retrieved_chunk": " * await pipe(\n * AsyncResult.tryCatch(() => doHttpThing(\"/cats\")), // AsyncResult<number, Error>\n * AsyncResult.mapErr(e => e.message), // AsyncResult<number, string>\n * Async.start // Promise<Result<number, string>>\n * )\n * // yields `Result.ok(number)` if the call succeeded\n * // otherwise yields `Result.err(string)`\n * ```\n */\nexport function tryCatch<A>(mightThrow: Async<A>): AsyncResult<A, Error>",
"score": 14.152917074242527
}
] | typescript | Array.find(val => toTrimmedLowerCase(val) === testVal),
Option.match({ |
/**
* 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": 44.24574381095221
},
{
"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": 38.63693112313088
},
{
"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": 35.98988354117652
},
{
"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": 34.92144966660081
},
{
"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": 34.73668986366594
}
] | typescript | r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { |
/**
* 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": " */\nexport const concatFirst =\n <A>(addToFront: readonly A[]) =>\n (as: readonly A[]): readonly A[] =>\n [...addToFront, ...as]\n/**\n * Returns true if at least one element of the array\n * satisfies the given predicate. Curried version of\n * `Array.prototype.some`.\n *",
"score": 41.42891152955691
},
{
"filename": "src/Composition.ts",
"retrieved_chunk": "### Examples\nFunction composition with `pipe` is the primary motivation for using currying and partially applying\nfunctions. Consider the following annotated code example:\n```ts\n// lets assume we have access to some basic string functions with these signatures\ndeclare const capitalize: (s: string) => string\ndeclare const exclaim: (s: string) => string\ndeclare const duplicate: (s: string) => [string, string]\n// note that the following functions are curried\ndeclare const split: (splitter: string) => (s: string) => string[]",
"score": 40.580293236237544
},
{
"filename": "src/NonEmptyArray.ts",
"retrieved_chunk": "/**\n * A `NonEmptyArray` is an array that is guaranteed by the type system to have\n * at least one element. This type is useful for correctly modeling certain\n * behaviors where empty arrays are absurd. It also makes it safer to work with\n * functionality like destructuring the array or getting the first value.\n *\n * **Note:** A `NonEmptyArray` is just a _more specific_ type of readonly array,\n * so any functions from the `Array` module can also be used with `NonEmptyArray`s.\n *\n * @module NonEmptyArray",
"score": 39.93796718427777
},
{
"filename": "src/NonEmptyArray.ts",
"retrieved_chunk": " */\nimport { EqualityComparer } from \"./EqualityComparer\"\nimport { OrderingComparer } from \"./OrderingComparer\"\n/** Represents a readonly array with at least one element. */\nexport interface NonEmptyArray<A> extends ReadonlyArray<A> {\n 0: A\n}\n/**\n * Get the first element of a non-empty array.\n *",
"score": 39.58066897959709
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " * Filter a `Result` using a type guard (a.k.a. `Refinement` function) that, if\n * it succeeds, will return an `Ok` with a narrowed type. If it fails, will use\n * the given `onFail` function to produce an error branch.\n *\n * @group Utils\n * @group Filtering\n *\n * @example\n * ```\n * const isCat = (s: string): s is \"cat\" => s === \"cat\"",
"score": 34.97721892218852
}
] | 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": 36.95341376605264
},
{
"filename": "src/AsyncResult.ts",
"retrieved_chunk": " <A, E>(result: Result<A, E>): AsyncResult<A, E> =>\n () =>\n Promise.resolve(result)\n/**\n * Use this function to \"lift\" an `Async` computation into an `AsyncResult`.\n * Essentially, this just wraps the `Async`'s inner value into a `Result.ok`.\n *\n * @group Utils\n * @group Constructors\n */",
"score": 36.251904790678545
},
{
"filename": "src/AsyncResult.ts",
"retrieved_chunk": " * @returns The `AsyncResult`, unchanged.\n *\n * @group Utils\n */\nexport const tee =\n <A>(f: (a: A) => void) =>\n <E>(async: AsyncResult<A, E>): AsyncResult<A, E> =>\n Async.tee<Result<A, E>>(Result.tee(f))(async)\n/**\n * Execute an arbitrary side-effect on the inner `Err` value of an `AsyncResult`",
"score": 35.115398478845016
},
{
"filename": "src/AsyncResult.ts",
"retrieved_chunk": " * just `Async`s with a constrained inner value type.\n *\n * @module AsyncResult\n */\nimport { Result } from \"./Result\"\nimport { Async } from \"./Async\"\nimport { pipe } from \"./Composition\"\n/**\n * @typeParam A The type of the `Ok` branch.\n * @typeParam E The type of the `Err` branch.",
"score": 33.085705741289345
},
{
"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": 32.633913081983074
}
] | 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/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": 122.11265564948745
},
{
"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": 84.97945068613815
},
{
"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": 78.33834526058457
},
{
"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": 76.15499986500522
},
{
"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": 72.24330327841625
}
] | 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/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": 51.6399933415056
},
{
"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": 47.339479601428415
},
{
"filename": "src/NonEmptyArray.ts",
"retrieved_chunk": " if (arr1.length !== arr2.length) {\n return false\n }\n for (let i = 0; i < arr1.length; i++) {\n if (!equals(arr1[i], arr2[i])) {\n return false\n }\n }\n return true\n })",
"score": 42.25867957942914
},
{
"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": 42.01060373177163
},
{
"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": 41.10297567984031
}
] | 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": "export const mapErr =\n <E1, E2>(f: (e: E1) => E2) =>\n <A>(result: Result<A, E1>) =>\n pipe(\n result,\n match({\n ok: a => ok(a),\n err: e => err(f(e)),\n })\n )",
"score": 39.453541612429376
},
{
"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": 37.919302821757135
},
{
"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": 35.69789477030502
},
{
"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": 30.68129345602033
},
{
"filename": "src/Async.ts",
"retrieved_chunk": " * const a = await Async.of(1)(); // => 1\n * // use a named function, useful for pipelining\n * const b = await pipe(\n * Async.of(1),\n * Async.start\n * ) // => 1\n */\nexport const start = <A>(async: Async<A>): Promise<A> => async()\n/**\n * Converts an array of `Async` computations into one `Async` computation",
"score": 28.760827141964874
}
] | 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/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": 90.69048382185186
},
{
"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": 83.69065593804234
},
{
"filename": "src/Composition.ts",
"retrieved_chunk": " ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E\n): E\nexport function pipe<A, B, C, D, E, F>(\n a: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,",
"score": 71.90463000589344
},
{
"filename": "src/Composition.ts",
"retrieved_chunk": "export function flow<A extends ReadonlyArray<unknown>, B, C, D, E>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E\n): (...a: A) => E\nexport function flow<A extends ReadonlyArray<unknown>, B, C, D, E, F>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,",
"score": 70.96284632415161
},
{
"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": 68.3643033722057
}
] | 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": 70.08212291888182
},
{
"filename": "src/Option.ts",
"retrieved_chunk": " * Get an `EqualityComparer` for an `Option<A>` by giving this function an\n * `EqualityComparer` for type `A`. Represents structural (value-based) equality\n * for the `Option` type.\n *\n * @group Equality\n * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for the inner value.\n * @returns A new `EqualityComparer` instance\n */",
"score": 65.75820554293125
},
{
"filename": "src/Array.ts",
"retrieved_chunk": " * of type `A` by giving this function an `EqualityComparer` for each `A` element.\n *\n * @group Equality\n * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison.\n *\n * @returns A new `EqualityComparer` instance\n *\n * @example",
"score": 55.926863003044666
},
{
"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`→`A`.\n *\n * @returns A new `EqualityComparer` instance.\n */\nexport const deriveFrom = <A, B>(",
"score": 49.018787344049834
},
{
"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": 40.50331348073561
}
] | typescript | EqualityComparer.ofEquals((r1, r2) => { |
/**
* 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/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": 51.6399933415056
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " *\n * @group Mapping\n */\nexport const map2 =\n <A, B, C>(map: (a: A, b: B) => C) =>\n <E>(results: readonly [Result<A, E>, Result<B, E>]): Result<C, E> => {\n if (isOk(results[0]) && isOk(results[1])) {\n return ok(map(results[0].ok, results[1].ok))\n } else if (isErr(results[0])) {\n return err(results[0].err)",
"score": 46.31979584978846
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " <A, B, C, D>(map: (a: A, b: B, c: C) => D) =>\n <E>(results: readonly [Result<A, E>, Result<B, E>, Result<C, E>]): Result<D, E> => {\n if (isOk(results[0]) && isOk(results[1]) && isOk(results[2])) {\n return ok(map(results[0].ok, results[1].ok, results[2].ok))\n } else if (isErr(results[0])) {\n return err(results[0].err)\n } else if (isErr(results[1])) {\n return err(results[1].err)\n } else {\n return err((results[2] as Err<E>).err)",
"score": 43.470221091767804
},
{
"filename": "src/Composition.ts",
"retrieved_chunk": "declare const join: (joiner: string) => (as: string[]) => string\ndeclare const map: <A, B>(f: (a: A) => B) => (as: A[]) => B[]\ndeclare const flatMap: <A, B>(f: (a: A) => B[]) => (as: A[]) => B[]\nconst result = pipe(\n \"hello there\",\n split(\" \"), // [\"hello\", \"there\"]\n map(s => pipe(s, capitalize, exclaim)), // [\"Hello!\", \"There!\"]\n flatMap(duplicate), // [\"Hello!\", \"Hello!\", \"There!\", \"There!\"]\n join(\"<>\") // \"Hello!<>Hello!<>There!<>There!\"\n);",
"score": 43.151055649947985
},
{
"filename": "src/NonEmptyArray.ts",
"retrieved_chunk": " if (arr1.length !== arr2.length) {\n return false\n }\n for (let i = 0; i < arr1.length; i++) {\n if (!equals(arr1[i], arr2[i])) {\n return false\n }\n }\n return true\n })",
"score": 42.25867957942914
}
] | typescript | if (Result.isOk(result)) { |
/**
* 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.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": 55.80293906802795
},
{
"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": 45.80150513273409
},
{
"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": 44.69406832219391
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " */\nexport const bind = <A, E, B>(f: (a: A) => Result<B, E>) =>\n match<A, E, Result<B, E>>({\n ok: f,\n err: e => err(e),\n })\n/**\n * Alias for {@link bind}.\n *\n * @group Mapping",
"score": 39.84230365964342
},
{
"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": 36.42730188637286
}
] | typescript | Async.tee<Result<A, E>>(Result.teeErr(f))(async)
/* c8 ignore start */
/** @ignore */
export const AsyncResult = { |
/**
* 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": " ? 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": 70.50923805850333
},
{
"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": 67.63656661968474
},
{
"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": 57.506883270163875
},
{
"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": 47.44809754742204
},
{
"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": 45.90924403710891
}
] | 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": 34.40213769561989
},
{
"filename": "src/Result.ts",
"retrieved_chunk": "export const mapErr =\n <E1, E2>(f: (e: E1) => E2) =>\n <A>(result: Result<A, E1>) =>\n pipe(\n result,\n match({\n ok: a => ok(a),\n err: e => err(f(e)),\n })\n )",
"score": 34.052485855852616
},
{
"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": 31.900316129601123
},
{
"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": 28.103851331329082
},
{
"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": 27.386506957239767
}
] | 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/Array.ts",
"retrieved_chunk": " * @example\n * pipe(\n * [32, null, 55, undefined, 89], // (number | null | undefined)[]\n * Array.chooseR(x => pipe(\n * x, // number | null | undefined\n * Option.ofNullish, // Option<number>\n * Option.map(String), // Option<string>\n * Result.ofOption(() => \"err\") // Result<string, string>\n * )) // string[]\n * ) // => [\"32\", \"55\", \"89\"]",
"score": 21.491568198044387
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " * pipe(\n * Result.ok(\"dog\"),\n * Result.refine(isCat, a => `\"${a}\" is not \"cat\"!`)\n * ) // => Result.err('\"dog\" is not \"cat\"!')\n * ```\n */\nexport const refine =\n <A, B extends A, E>(refinement: Refinement<A, B>, onFail: (a: A) => E) =>\n (result: Result<A, E>): Result<B, E> =>\n pipe(",
"score": 16.614565623272878
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " tee,\n teeErr,\n ofOption,\n getEqualityComparer,\n refine,\n}\n/* c8 ignore end */",
"score": 14.912500567211506
},
{
"filename": "src/Array.ts",
"retrieved_chunk": " * @example\n * pipe(\n * [32, null, 55, undefined, 89], // (number | null | undefined)[]\n * Array.choose(x => pipe(\n * x, // number | null | undefined\n * Option.ofNullish, // Option<number>\n * Option.map(String) // Option<string>\n * )) // string[]\n * ) // => [\"32\", \"55\", \"89\"]\n */",
"score": 11.64040891796337
},
{
"filename": "src/Nullable.ts",
"retrieved_chunk": " * ) // => \"!yoha¡\", if str is \"ahoy\"; \"\" if str is null or undefined\n * ```\n *\n * @module Nullable\n */\nimport { EqualityComparer } from \"./EqualityComparer\"\nimport { NonNullish } from \"./prelude\"\nexport type Nullable<A extends NonNullish> = A | null | undefined\n/**\n * Get an `EqualityComparer` that considers `null` and `undefined` equivalent, and",
"score": 10.96754887234465
}
] | 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/Array.ts",
"retrieved_chunk": " * @example\n * pipe(\n * [32, null, 55, undefined, 89], // (number | null | undefined)[]\n * Array.chooseR(x => pipe(\n * x, // number | null | undefined\n * Option.ofNullish, // Option<number>\n * Option.map(String), // Option<string>\n * Result.ofOption(() => \"err\") // Result<string, string>\n * )) // string[]\n * ) // => [\"32\", \"55\", \"89\"]",
"score": 22.29755769268663
},
{
"filename": "src/Array.ts",
"retrieved_chunk": " * @example\n * pipe(\n * [32, null, 55, undefined, 89], // (number | null | undefined)[]\n * Array.choose(x => pipe(\n * x, // number | null | undefined\n * Option.ofNullish, // Option<number>\n * Option.map(String) // Option<string>\n * )) // string[]\n * ) // => [\"32\", \"55\", \"89\"]\n */",
"score": 17.201516116921255
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " * value. Pass a matcher function with cases for `ok` and `err` that\n * can either be lambdas or raw values.\n *\n * @group Pattern Matching\n *\n * @example\n * ```\n * pipe(\n * Result.err(\"failure\"),\n * Result.match({",
"score": 15.217992748603344
},
{
"filename": "src/Result.ts",
"retrieved_chunk": " * @group Mapping\n *\n * @example\n * pipe(\n * Result.ok(\"a\"),\n * Result.bind(s =>\n * s === \"a\" ? Result.ok(\"got an a!\") : Result.err(\"not an a\")\n * ),\n * Result.defaultValue(\"\")\n * ) // => \"got an a!\"",
"score": 14.517045940775231
},
{
"filename": "src/AsyncResult.ts",
"retrieved_chunk": " * await pipe(\n * AsyncResult.tryCatch(() => doHttpThing(\"/cats\")), // AsyncResult<number, Error>\n * AsyncResult.mapErr(e => e.message), // AsyncResult<number, string>\n * Async.start // Promise<Result<number, string>>\n * )\n * // yields `Result.ok(number)` if the call succeeded\n * // otherwise yields `Result.err(string)`\n * ```\n */\nexport function tryCatch<A>(mightThrow: Async<A>): AsyncResult<A, Error>",
"score": 14.152917074242527
}
] | 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": 107.52886553083717
},
{
"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": 105.71543508409044
},
{
"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": 103.94850115967799
},
{
"filename": "src/Deferred.ts",
"retrieved_chunk": "}\n/** @ignore */\ninterface PartialDeferredMatcher<A, R> extends Partial<DeferredMatcher<A, R>> {\n readonly orElse: (() => R) | R\n}\ntype Func<T> = (...args: any[]) => T\ntype FuncOrValue<T> = Func<T> | T\nconst resultOrValue = <T>(f: FuncOrValue<T>, ...args: any[]) => {\n const isFunc = (f: FuncOrValue<T>): f is Func<T> => typeof f === \"function\"\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument",
"score": 62.496612381710136
},
{
"filename": "src/Enums.ts",
"retrieved_chunk": "type RawEnum = Record<string, string | number>\n/** @ignore */\ntype StringKeyValues<T extends RawEnum> = Identity<T[StringKeys<T>]>\n/** @ignore */\ntype EnumMatcher<A, R extends RawEnum> = {\n readonly [Label in StringKeys<R>]: (() => A) | A\n}\n/** @ignore */\ntype PartialEnumMatcher<A, R extends RawEnum> = Partial<EnumMatcher<A, R>> & {\n readonly orElse: (() => A) | A",
"score": 55.37908137153609
}
] | typescript | nonEmpty: ((as: NonEmptyArray<A>) => R) | R
} |
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": 27.654493196316984
},
{
"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": 25.129049463625698
},
{
"filename": "src/provider.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 Impl<FooComponent | BarComponent, [BazComponent]>,\n | Provider<\"foo\", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>\n | Provider<\"bar\", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>\n >\n >();",
"score": 24.27864778675356
},
{
"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": 23.41615363302763
},
{
"filename": "src/component.spec.ts",
"retrieved_chunk": " Mixed<[FooComponent, BarComponent] | [BazComponent]>,\n | Readonly<{\n foo: { getFoo: () => number };\n bar: { getBar: () => string };\n }>\n | Readonly<{\n baz: { getBaz: () => boolean };\n }>\n >\n >();",
"score": 21.86344942488253
}
] | typescript | m = mixer(foo, bar, baz); |
/**
* 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/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": 119.81566744641403
},
{
"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": 110.3700790925833
},
{
"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": 88.2164701953241
},
{
"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": 84.35098582091452
},
{
"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": 68.9888140604009
}
] | typescript | export interface NotStarted extends Tagged<"NotStarted", object> {} |
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": " 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": 34.167073762565124
},
{
"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": 33.96234483556
},
{
"filename": "src/provider.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 Impl<FooComponent | BarComponent, [BazComponent]>,\n | Provider<\"foo\", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>\n | Provider<\"bar\", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>\n >\n >();",
"score": 33.249126566809565
},
{
"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": 32.537756053032304
},
{
"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": 31.309115240431762
}
] | typescript | foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ |
/**
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/string.ts",
"retrieved_chunk": " * @returns boolean\n */\nexport const isString = (u: unknown): u is string => typeof u === \"string\"\n/**\n * Get the length of a string.\n *\n * @group Utils\n */\nexport const length = (s: string) => s.length\n/**",
"score": 85.44061047160874
},
{
"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": 82.49026668648204
},
{
"filename": "src/string.ts",
"retrieved_chunk": " * Curried version of the built-in toUpperCase method.\n *\n * @group Utils\n */\nexport const toUpperCase = (s: string) => s.toUpperCase()\n/**\n * Type guard that holds true when `u` is a string.\n *\n * @group Type Guards\n *",
"score": 49.65686263396152
},
{
"filename": "src/Array.ts",
"retrieved_chunk": " * @example\n * pipe(\n * [32, null, 55, undefined, 89], // (number | null | undefined)[]\n * Array.chooseR(x => pipe(\n * x, // number | null | undefined\n * Option.ofNullish, // Option<number>\n * Option.map(String), // Option<string>\n * Result.ofOption(() => \"err\") // Result<string, string>\n * )) // string[]\n * ) // => [\"32\", \"55\", \"89\"]",
"score": 42.332792168199745
},
{
"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": 30.858629935519197
}
] | typescript | Result.ofOption(
() =>
`Enum${ |
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": "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": 37.36139789220954
},
{
"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": 37.18812033773306
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 34.71370518195446
},
{
"filename": "src/mixer.ts",
"retrieved_chunk": " [N in keyof D]: N extends keyof I\n ? never\n : {\n name: N;\n expectedType: D[N];\n };\n }[keyof D]\n >\n : never;\ntype IncompatibleDependenciesError<",
"score": 30.361238858750617
},
{
"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": 29.02067324317823
}
] | typescript | = Merge<Prod<FilteredInstances<Cs, [], never>>>; |
/**
* 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/Array.ts",
"retrieved_chunk": " <A>(a: A, equalityComparer: EqualityComparer<A> = EqualityComparer.Default) =>\n (as: readonly A[]): boolean => {\n if (isEmpty(as)) {\n return false\n }\n const predicate = (test: A) => equalityComparer.equals(a, test)\n return as.some(predicate)\n }\n/**\n * Return a new array containing only unique values. If",
"score": 29.454632928964806
},
{
"filename": "src/EqualityComparer.ts",
"retrieved_chunk": "export const Number: EqualityComparer<number> = Default\n/* c8 ignore start */\n/** @ignore */\nexport const EqualityComparer = {\n ofEquals,\n ofStruct,\n deriveFrom,\n Default,\n Date,\n String,",
"score": 27.237609533201372
},
{
"filename": "src/Map.ts",
"retrieved_chunk": " * @returns `true` if the key is in the `Map`, `false` otherwise.\n */\nexport const containsKey =\n <K>(key: K, equalityComparer: EqualityComparer<K> = EqualityComparer.Default) =>\n <V>(map: ReadonlyMap<K, V>): boolean =>\n pipe(map, findWithKey(key, equalityComparer), Option.isSome)\n/**\n * Get a value associated with the given key from the `Map`. Returns a `Some`\n * containing the value, or `None` if the key is not in the `Map`.\n *",
"score": 25.100747739553203
},
{
"filename": "src/Map.ts",
"retrieved_chunk": " * returned unchanged if the key is not found in the map.\n *\n * @group Transformations\n */\nexport const remove =\n <K>(key: K, equalityComparer: EqualityComparer<K> = EqualityComparer.Default) =>\n <V>(map: ReadonlyMap<K, V>) =>\n pipe(\n map,\n findWithKey(key, equalityComparer),",
"score": 22.996165145958685
},
{
"filename": "src/Nullable.ts",
"retrieved_chunk": " * compares non-nullish values based on the given `EqualityComparer`.\n *\n * @group Utils\n *\n * @example\n * ```\n * const { equals } = Nullable.getEqualityComparer(EqualityComparer.Number)\n * equals(null, undefined) // => true\n * equals(3, undefined) // => false\n * equals(null, 4) // => false",
"score": 22.84116801738519
}
] | typescript | equalityComparer: EqualityComparer<A> = EqualityComparer.Default
) =>
matchOrElse<A, boolean>({ |
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": 24.283044896940503
},
{
"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": 18.89655093585021
},
{
"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": 18.635305623200964
},
{
"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": 18.524407315507556
},
{
"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": 18.429252714450246
}
] | typescript | ReconstructComponent<FooProvider>, Component<"foo", { getFoo: () => number }>>
>(); |
/**
* 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/Array.ts",
"retrieved_chunk": " * of type `A` by giving this function an `EqualityComparer` for each `A` element.\n *\n * @group Equality\n * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison.\n *\n * @returns A new `EqualityComparer` instance\n *\n * @example",
"score": 61.682024265483854
},
{
"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": 52.61260058605675
},
{
"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": 48.237320998927004
},
{
"filename": "src/Option.ts",
"retrieved_chunk": " * Get an `EqualityComparer` for an `Option<A>` by giving this function an\n * `EqualityComparer` for type `A`. Represents structural (value-based) equality\n * for the `Option` type.\n *\n * @group Equality\n * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for the inner value.\n * @returns A new `EqualityComparer` instance\n */",
"score": 43.40702146571747
},
{
"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": 39.12240765159553
}
] | typescript | EqualityComparer<A>): EqualityComparer<NonEmptyArray<A>> =>
EqualityComparer.ofEquals((arr1, arr2) => { |
/**
* 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": 120.65402927288419
},
{
"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": 110.05132141139626
},
{
"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": 75.09273333211803
},
{
"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": 73.65785083870537
},
{
"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": 64.5065677699027
}
] | typescript | export interface Ok<A> extends Tagged<"Ok", { ok: A }> {} |
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": "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": 37.36139789220954
},
{
"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": 37.18812033773306
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 34.71370518195446
},
{
"filename": "src/mixer.ts",
"retrieved_chunk": " [N in keyof D]: N extends keyof I\n ? never\n : {\n name: N;\n expectedType: D[N];\n };\n }[keyof D]\n >\n : never;\ntype IncompatibleDependenciesError<",
"score": 30.361238858750617
},
{
"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": 29.02067324317823
}
] | 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/mixer.ts",
"retrieved_chunk": " const instances = new Map<string, unknown>();\n const getters = new Map<string, () => unknown>();\n const lock = new Set<string>();\n for (const { name, factory } of providers) {\n const getter = (): unknown => {\n if (instances.has(name)) {\n return instances.get(name);\n }\n if (lock.has(name)) {\n throw new Error(`'${name}' is referenced during its initialization`);",
"score": 60.32853286352096
},
{
"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": 36.49929881688813
},
{
"filename": "src/provider.spec.ts",
"retrieved_chunk": " expect(value.getFoo()).toBe(42);\n });\n it(\"calls the constructor of the argument if it is a class\", () => {\n const factory = class Foo {\n private foo: number;\n constructor(foo: number) {\n this.foo = foo;\n }\n getFoo(): number {\n return this.foo;",
"score": 30.713641793123923
},
{
"filename": "src/provider.ts",
"retrieved_chunk": " deps: D\n): T {\n // check if the factory is a class (not a perfect check though)\n const desc = Object.getOwnPropertyDescriptor(factory, \"prototype\");\n if (desc && !desc.writable) {\n // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion\n return new (factory as FactoryClass<T, D>)(deps);\n } else {\n // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion\n return (factory as FactoryFunction<T, D>)(deps);",
"score": 30.31730460047934
},
{
"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": 30.236686329441728
}
] | typescript | bar", deps => ({ |
/**
* 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": " ? 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": 60.69204831505743
},
{
"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": 58.03714368616369
},
{
"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": 53.457800696079836
},
{
"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": 44.67784948370016
},
{
"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": 42.906531290632756
}
] | typescript | assertExhaustive(deferred) as R
} |
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": " 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": 34.167073762565124
},
{
"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": 33.96234483556
},
{
"filename": "src/provider.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 Impl<FooComponent | BarComponent, [BazComponent]>,\n | Provider<\"foo\", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>\n | Provider<\"bar\", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>\n >\n >();",
"score": 33.249126566809565
},
{
"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": 32.537756053032304
},
{
"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": 31.309115240431762
}
] | typescript | [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ |
/**
* 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`→`A`, not from `A`→`B`.
*
* @group Utils
* @group Constructors
*
* @param known The `OrderingComparer` that you already have.
* @param map The function that can map from `B`→`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": " */\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": 43.0114749733809
},
{
"filename": "src/Array.ts",
"retrieved_chunk": " * OrderingComparer that `String`s the mapped element and uses the\n * default ASCII-based sort.\n *\n * @group Utils\n */\nexport const sortBy =\n <A, B>(\n f: (a: A) => B,\n orderingComparer: OrderingComparer<B> = OrderingComparer.Default\n ) =>",
"score": 36.58531513454723
},
{
"filename": "src/NonEmptyArray.ts",
"retrieved_chunk": " */\nimport { EqualityComparer } from \"./EqualityComparer\"\nimport { OrderingComparer } from \"./OrderingComparer\"\n/** Represents a readonly array with at least one element. */\nexport interface NonEmptyArray<A> extends ReadonlyArray<A> {\n 0: A\n}\n/**\n * Get the first element of a non-empty array.\n *",
"score": 35.090509431074196
},
{
"filename": "src/EqualityComparer.ts",
"retrieved_chunk": " * - `myEqComparer.equals(a, b) === myEqComparer.equals(b, a)`\n * 1. should be transitive such that if `a` = `b` and `b` = `c`, then `a` = `c`\n *\n * **Note:** An `EqualityComparer` is structurally compatible with the `Eq` type from `fp-ts`.\n *\n * @example\n * interface Pet {\n * readonly name: string\n * readonly age: number\n * }",
"score": 34.312090885484004
},
{
"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": 31.923822874809233
}
] | typescript | ): OrderingComparer<A> & EqualityComparer<A> => ({ |
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": " >();\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": 18.256674855133635
},
{
"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": 17.84319170425318
},
{
"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": 16.24045656873219
},
{
"filename": "src/provider.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 Impl<FooComponent | BarComponent, [BazComponent]>,\n | Provider<\"foo\", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>\n | Provider<\"bar\", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>\n >\n >();",
"score": 15.809411118168002
},
{
"filename": "src/mixer.spec.ts",
"retrieved_chunk": " const m = mixer(foo, bar, baz);\n assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>();\n const mixed = m.new();\n assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>();\n expect(mixed.foo.getFoo()).toBe(5);\n });\n it(\"overrides previous mixed components\", () => {\n const foo = impl<FooComponent, [BarComponent, BazComponent]>(\"foo\", ({ bar, baz }) => ({\n getFoo: () => (baz.getBaz() ? bar.getBar().length : 42),\n }));",
"score": 14.534743664798345
}
] | typescript | <Equals<Mixed<[]>, {}>>(); |
/**
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": 54.422922756374966
},
{
"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": 52.217252927454176
},
{
"filename": "src/Variants.ts",
"retrieved_chunk": "type EmptyObjGuard<T> = T extends ObjectGuard<infer O>\n ? object extends O\n ? O\n : never\n : never\ntype Scoped<T extends string, Scope extends string = \"\"> = Scope extends \"\"\n ? T\n : `${Scope}${T}`\ntype ObjectGuard<T extends object> = Exclude<T, any[] | Func>\ntype NonEmptyStringKeys<T> = Exclude<Extract<keyof T, string>, \"\">",
"score": 50.73505320237626
},
{
"filename": "src/Variants.ts",
"retrieved_chunk": " Scope extends string = DefaultScope\n> = ObjectGuard<CaseReturnType<T>> extends never\n ? [never, \"Only objects are allowed as variant data. Wrap variant data in an object.\"]\n : T extends Func\n ? VariantConstructor<Parameters<T>, Case, CaseReturnType<T>, Discriminant, Scope>\n : Variant<Case, CaseReturnType<T>, Discriminant, Scope>\ntype VariantConstructors<\n Input extends VariantInputObject = Record<string, never>,\n Discriminant extends string = DefaultDiscriminant,\n Scope extends string = DefaultScope",
"score": 44.69836750631647
},
{
"filename": "src/Variants.ts",
"retrieved_chunk": "/********************\n * Foundational Types\n *********************/\ntype VariantInputObject = Record<string, Func | object>\ntype Variant<\n Case extends string,\n Data extends object = object,\n Discriminant extends string = DefaultDiscriminant,\n Scope extends string = DefaultScope\n> = Identity<",
"score": 43.94213058231147
}
] | typescript | RawEnum> = Identity<T[StringKeys<T>]>
/** @ignore */
type EnumMatcher<A, R extends RawEnum> = { |
/**
* 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": 58.612547810333666
},
{
"filename": "src/Option.ts",
"retrieved_chunk": " * Get an `EqualityComparer` for an `Option<A>` by giving this function an\n * `EqualityComparer` for type `A`. Represents structural (value-based) equality\n * for the `Option` type.\n *\n * @group Equality\n * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for the inner value.\n * @returns A new `EqualityComparer` instance\n */",
"score": 46.637725674130465
},
{
"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": 43.05115561199914
},
{
"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": 42.472552908079784
},
{
"filename": "src/Array.ts",
"retrieved_chunk": " * of type `A` by giving this function an `EqualityComparer` for each `A` element.\n *\n * @group Equality\n * @group Utils\n *\n * @param equalityComparer The `EqualityComparer` to use for element-by-element comparison.\n *\n * @returns A new `EqualityComparer` instance\n *\n * @example",
"score": 41.90219876324695
}
] | typescript | if (isErr(r1) && isErr(r2) && equalityComparerE.equals(r1.err, r2.err)) { |
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": "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": 59.42967151136192
},
{
"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": 57.95771104978726
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 55.04167116737214
},
{
"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": 54.88314830940944
},
{
"filename": "src/provider.ts",
"retrieved_chunk": " name: N;\n factory: Factory<T, D>;\n}>;\nexport type Factory<T extends unknown, D extends unknown> =\n | FactoryFunction<T, D>\n | FactoryClass<T, D>;\nexport type FactoryFunction<T extends unknown, D extends unknown> = (deps: D) => T;\nexport type FactoryClass<T extends unknown, D extends unknown> = new (deps: D) => T;\nexport function invokecFactory<T extends unknown, D extends unknown>(\n factory: Factory<T, D>,",
"score": 51.664783274002616
}
] | typescript | export type Mixed<Cs extends AbstractComponent[]> = 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": 42.99364315396056
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": " border-radius: 2px;\n width: 30px;\n height: 30px;\n display: none;\n @media (max-width: 600px) {\n display: block;\n }\n`;\nconst InfoContainer = styled.div`\n display: flex;",
"score": 26.036577714263252
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": "const CoffeeButton = styled.button`\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: center;\n background: #d4b9ff;\n gap: 10px;\n border: 1px solid #000000;\n border-radius: 5px;\n font-weight: 700;",
"score": 19.47466444093215
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": " margin: 0;\n font-size: 15px;\n color: #6c6c6c;\n padding-left: 4px;\n`;\nconst EventImage = styled.img`\n max-width: 111px;\n max-height: 74px;\n border-radius: 5px;\n`;",
"score": 18.49142491847065
},
{
"filename": "src/api/index.ts",
"retrieved_chunk": " };\n }\n const path = event.requestContext.http.path;\n const method = event.requestContext.http.method.toUpperCase();\n let controller = undefined as undefined | Controller;\n for (const route of routes) {\n if (method === route.method && new RegExp(`^${route.path}$`).test(path)) {\n controller = route.controller;\n break;\n }",
"score": 17.92970546256209
}
] | typescript | ] = useState(undefined as undefined | EventStats); |
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/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": 20.045253106920086
},
{
"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": 18.734011164092756
},
{
"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": 16.307462031731887
},
{
"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": 15.295629226021365
},
{
"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": 15.000938659067831
}
] | typescript | url: `${AppConf.githubApiBaseUrl}/repos/${repo}/issues`,
method: "POST",
headers: { |
/**
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/string.ts",
"retrieved_chunk": " * @returns boolean\n */\nexport const isString = (u: unknown): u is string => typeof u === \"string\"\n/**\n * Get the length of a string.\n *\n * @group Utils\n */\nexport const length = (s: string) => s.length\n/**",
"score": 60.41812573343187
},
{
"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": 58.47179415989953
},
{
"filename": "src/Array.ts",
"retrieved_chunk": " * @example\n * pipe(\n * [32, null, 55, undefined, 89], // (number | null | undefined)[]\n * Array.chooseR(x => pipe(\n * x, // number | null | undefined\n * Option.ofNullish, // Option<number>\n * Option.map(String), // Option<string>\n * Result.ofOption(() => \"err\") // Result<string, string>\n * )) // string[]\n * ) // => [\"32\", \"55\", \"89\"]",
"score": 34.6317238020702
},
{
"filename": "src/string.ts",
"retrieved_chunk": " * Curried version of the built-in toUpperCase method.\n *\n * @group Utils\n */\nexport const toUpperCase = (s: string) => s.toUpperCase()\n/**\n * Type guard that holds true when `u` is a string.\n *\n * @group Type Guards\n *",
"score": 32.81479904668395
},
{
"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": 28.480244852973424
}
] | typescript | ofNullish(u),
Result.ofOption(
() =>
`Enum${ |
/**
* 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/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": 124.26048072160022
},
{
"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": 87.22529805355724
},
{
"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": 79.72401846505036
},
{
"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": 76.15499986500522
},
{
"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": 72.24330327841625
}
] | typescript | return err(results[1].err)
} else { |
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": 42.99364315396056
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": " border-radius: 2px;\n width: 30px;\n height: 30px;\n display: none;\n @media (max-width: 600px) {\n display: block;\n }\n`;\nconst InfoContainer = styled.div`\n display: flex;",
"score": 19.431144495456564
},
{
"filename": "src/api/index.ts",
"retrieved_chunk": " };\n }\n const path = event.requestContext.http.path;\n const method = event.requestContext.http.method.toUpperCase();\n let controller = undefined as undefined | Controller;\n for (const route of routes) {\n if (method === route.method && new RegExp(`^${route.path}$`).test(path)) {\n controller = route.controller;\n break;\n }",
"score": 17.92970546256209
},
{
"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": 16.7381246577274
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": " margin: 0;\n font-size: 15px;\n color: #6c6c6c;\n padding-left: 4px;\n`;\nconst EventImage = styled.img`\n max-width: 111px;\n max-height: 74px;\n border-radius: 5px;\n`;",
"score": 15.420776618077468
}
] | typescript | ).then((events) => { |
/**
* 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/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": 90.69048382185186
},
{
"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": 83.69065593804234
},
{
"filename": "src/Composition.ts",
"retrieved_chunk": " ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E\n): E\nexport function pipe<A, B, C, D, E, F>(\n a: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,",
"score": 71.90463000589344
},
{
"filename": "src/Composition.ts",
"retrieved_chunk": "export function flow<A extends ReadonlyArray<unknown>, B, C, D, E>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E\n): (...a: A) => E\nexport function flow<A extends ReadonlyArray<unknown>, B, C, D, E, F>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,",
"score": 70.96284632415161
},
{
"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": 68.3643033722057
}
] | typescript | 2].ok))
} else if (isErr(results[0])) { |
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-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": 21.957354680231752
},
{
"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": 21.407454115120196
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": "};\nexport type Controller = (\n event: APIGatewayProxyEventV2\n) =>\n | APIGatewayProxyStructuredResultV2\n | Promise<APIGatewayProxyStructuredResultV2>;\nexport const routes: Array<Route> = [\n {\n method: \"GET\",\n path: \"/info/events\",",
"score": 20.395451699431778
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": " controller: chaptersController,\n },\n {\n method: \"GET\",\n path: \"/info/chapter-icons/[A-Za-z-]+\",\n controller: chapterIconController,\n },\n {\n method: \"GET\",\n path: \"/info/health\",",
"score": 20.21523097900229
},
{
"filename": "src/api/dao/email.dao.ts",
"retrieved_chunk": " method: \"POST\",\n url: AppConf.emailAppUrl,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: email,\n });\n}",
"score": 19.018398612639935
}
] | typescript | let controller = undefined as undefined | Controller; |
/**
* 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/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": 55.75784858975522
},
{
"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": 51.99670367871909
},
{
"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": 51.0774464780995
},
{
"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": 45.8162735445724
},
{
"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": 42.260009033724614
}
] | typescript | return assertExhaustive(result)
} |
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": 63.01642298416917
},
{
"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": 38.91581211463299
},
{
"filename": "src/api/index.ts",
"retrieved_chunk": " };\n }\n const path = event.requestContext.http.path;\n const method = event.requestContext.http.method.toUpperCase();\n let controller = undefined as undefined | Controller;\n for (const route of routes) {\n if (method === route.method && new RegExp(`^${route.path}$`).test(path)) {\n controller = route.controller;\n break;\n }",
"score": 35.785918751168104
},
{
"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": 24.21434696999787
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": "};\nexport type Controller = (\n event: APIGatewayProxyEventV2\n) =>\n | APIGatewayProxyStructuredResultV2\n | Promise<APIGatewayProxyStructuredResultV2>;\nexport const routes: Array<Route> = [\n {\n method: \"GET\",\n path: \"/info/events\",",
"score": 23.124337565712345
}
] | 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/api/dao/meetup.dao.ts",
"retrieved_chunk": "import { request } from \"../util/request.util\";\nimport { AppConf } from \"../app-conf\";\nimport { Chapter } from \"./settings.dao\";\n//See https://www.meetup.com/api/schema/#p03-objects-section for Meetup API details.\n/**\n * Represents all the data that is returned from the Meetup API for an event.\n */\nexport type MeetupEvent = {\n id: string;\n eventUrl: string;",
"score": 36.688989035275966
},
{
"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": 24.81475531340555
},
{
"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": 23.583474109182227
},
{
"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": 20.372874229313517
},
{
"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": 18.6494437325726
}
] | typescript | return request.headers?.["x-api-key"] === AppConf.apiKey; |
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": 22.480838001430904
},
{
"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": 19.58705188944481
},
{
"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": 19.16991172149088
},
{
"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": 18.641567315751153
},
{
"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": 17.828904228844326
}
] | typescript | : Chapter[]
): Promise<Array<MeetupEvent>> { |
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": " 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": 17.69286825360659
},
{
"filename": "src/getErrors.ts",
"retrieved_chunk": " targetObj.shouldRender = false\n targetObj.reason = getErrorReason(reason)\n return targetObj\n}\nconst invalidJSXMsg = 'itemShapes is not a valid JSX element'\ntype Props = Pick<RatingProps, 'items'> & Pick<ItemStyles, 'itemShapes'>\ntype ParamObj = Required<{\n [Prop in keyof Props]: unknown\n}>\nexport function getErrors({ items, itemShapes }: ParamObj) {",
"score": 14.81613146197215
},
{
"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": 11.343369107281406
},
{
"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": 11.030824051751852
},
{
"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": 9.00092751481997
}
] | typescript | shouldRender, reason } = 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": " 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": 12.500446689271184
},
{
"filename": "src/Rating.tsx",
"retrieved_chunk": " labelProps['aria-label'] = radioLabels[starIndex]\n }\n if (isDisabled) {\n labelProps['aria-disabled'] = 'true'\n }\n return {\n role: 'radio',\n 'aria-checked': starIndex + 1 === ratingValue,\n ...labelProps,\n }",
"score": 10.90292986744469
},
{
"filename": "src/constants.ts",
"retrieved_chunk": "type Classes = {\n [key: string]: CSSClassName\n}\nexport const RatingClasses: Classes = {\n GROUP: 'rr--group',\n BOX: 'rr--box',\n SVG: 'rr--svg',\n RESET: 'rr--reset',\n GROUP_RESET: 'rr--focus-reset',\n DEF_50: 'rr--svg-stop-1',",
"score": 9.388869692283265
},
{
"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": 9.37700957677787
},
{
"filename": "src/setColorCssVars.ts",
"retrieved_chunk": " return true\n case ActiveColorProps.BORDER:\n targetObj[ActiveVars.BORDER] = value\n return true\n case ActiveColorProps.STROKE:\n targetObj[ActiveVars.STROKE] = value\n return true\n }\n return false\n}",
"score": 8.673459213307048
}
] | 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/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": 31.85870651394849
},
{
"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": 25.166324560045002
},
{
"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": 24.102978264404477
},
{
"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": 20.20250464558643
},
{
"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": 17.853974349193052
}
] | 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/utils.ts",
"retrieved_chunk": "export const getUniqueId = () => (Math.random() + 1).toString(36).substring(7)\nexport const areNum = (...values: unknown[]) => values.every((value) => typeof value === 'number')\nexport const getNewPosition = (originalPos: number) =>\n originalPos === 0 ? 0 : toSecondDecimal(originalPos) * -1\nexport const isGraphicalValueInteger = (ratingValue: number) =>\n Number.isInteger(roundToHalf(ratingValue))\nexport function getIntersectionIndex(ratingValues: number[], ratingValue: number) {\n const roundedHalf = roundToHalf(ratingValue)\n if (Number.isInteger(roundedHalf)) {\n return ratingValues.indexOf(roundedHalf)",
"score": 28.952006747738057
},
{
"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": 12.004459186085718
},
{
"filename": "src/getHFClassNames.ts",
"retrieved_chunk": "import { roundToHalf } from './utils'\nimport { NonNullProp, CSSClassName } from './internalTypes'\nimport { HFClasses } from './constants'\nexport function getHFClassNames(\n ratingValue: NonNullProp<'value'>,\n items: NonNullProp<'items'>,\n absoluteHFMode: NonNullProp<'halfFillMode'>\n): CSSClassName[] {\n const intersectionIndex = Math.floor(roundToHalf(ratingValue))\n return Array.from({ length: items }, (_, index) => {",
"score": 11.204955417773478
},
{
"filename": "src/getColors.ts",
"retrieved_chunk": " }\n }\n return { arrayColors, staticColors: allColors as StaticColors }\n}",
"score": 10.67914924985571
},
{
"filename": "src/RatingItem.tsx",
"retrieved_chunk": " viewBox,\n translateData,\n })\n }\n }\n }, [itemShapes, itemStrokeWidth, hasHF])\n /* Props */\n function getHFAttr() {\n if (hasHF) {\n return {",
"score": 10.464469006085343
}
] | typescript | getColors(colors)
return { |
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/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": 37.33474709430983
},
{
"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": 25.166324560045002
},
{
"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": 24.102978264404477
},
{
"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": 20.20250464558643
},
{
"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": 17.853974349193052
}
] | typescript | export const Rating: typeof RatingComponent = forwardRef<HTMLDivElement, RatingProps>(
(
{ |
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": "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": 44.0570180291906
},
{
"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": 36.31588068671787
},
{
"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": 34.04302020116276
},
{
"filename": "src/ui/calendar/events.util.ts",
"retrieved_chunk": " result.totalRSVPs += event.going;\n if (!chapters.has(event.group.urlname)) {\n result.totalActiveChapters++;\n chapters.add(event.group.urlname);\n }\n });\n return result;\n}",
"score": 32.922031857957684
},
{
"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": 29.01780641272014
}
] | typescript | }:groupByUrlname(urlname:"${chapters[i].meetupGroupUrlName}") { ...groupFragment }`; |
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/constants.ts",
"retrieved_chunk": "type Classes = {\n [key: string]: CSSClassName\n}\nexport const RatingClasses: Classes = {\n GROUP: 'rr--group',\n BOX: 'rr--box',\n SVG: 'rr--svg',\n RESET: 'rr--reset',\n GROUP_RESET: 'rr--focus-reset',\n DEF_50: 'rr--svg-stop-1',",
"score": 16.098972628637707
},
{
"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": 15.953319140102803
},
{
"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": 14.60690881699783
},
{
"filename": "src/getGroupClassNames.ts",
"retrieved_chunk": " OrientationClasses,\n HasClasses,\n RatingClasses,\n OrientationProps,\n TransitionProps,\n} from './constants'\ntype ParamObj = Required<\n Pick<\n RatingProps,\n | 'className'",
"score": 14.017441405517879
},
{
"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": 13.2452156780213
}
] | typescript | stop className={RatingClasses.DEF_100} offset="50%" />
</linearGradient>
</defs>
)} |
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/routes.ts",
"retrieved_chunk": "};\nexport type Controller = (\n event: APIGatewayProxyEventV2\n) =>\n | APIGatewayProxyStructuredResultV2\n | Promise<APIGatewayProxyStructuredResultV2>;\nexport const routes: Array<Route> = [\n {\n method: \"GET\",\n path: \"/info/events\",",
"score": 25.951849590495183
},
{
"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": 22.80343155653083
},
{
"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": 21.407454115120196
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": " controller: chaptersController,\n },\n {\n method: \"GET\",\n path: \"/info/chapter-icons/[A-Za-z-]+\",\n controller: chapterIconController,\n },\n {\n method: \"GET\",\n path: \"/info/health\",",
"score": 20.21523097900229
},
{
"filename": "src/api/dao/email.dao.ts",
"retrieved_chunk": " method: \"POST\",\n url: AppConf.emailAppUrl,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: email,\n });\n}",
"score": 19.018398612639935
}
] | 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/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": 11.909510839895821
},
{
"filename": "src/Rating.tsx",
"retrieved_chunk": " labelProps['aria-label'] = radioLabels[starIndex]\n }\n if (isDisabled) {\n labelProps['aria-disabled'] = 'true'\n }\n return {\n role: 'radio',\n 'aria-checked': starIndex + 1 === ratingValue,\n ...labelProps,\n }",
"score": 10.261448663497056
},
{
"filename": "src/constants.ts",
"retrieved_chunk": "type Classes = {\n [key: string]: CSSClassName\n}\nexport const RatingClasses: Classes = {\n GROUP: 'rr--group',\n BOX: 'rr--box',\n SVG: 'rr--svg',\n RESET: 'rr--reset',\n GROUP_RESET: 'rr--focus-reset',\n DEF_50: 'rr--svg-stop-1',",
"score": 9.388869692283265
},
{
"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": 8.688409142336065
},
{
"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": 8.502373213535098
}
] | 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/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": 17.69286825360659
},
{
"filename": "src/getErrors.ts",
"retrieved_chunk": " targetObj.shouldRender = false\n targetObj.reason = getErrorReason(reason)\n return targetObj\n}\nconst invalidJSXMsg = 'itemShapes is not a valid JSX element'\ntype Props = Pick<RatingProps, 'items'> & Pick<ItemStyles, 'itemShapes'>\ntype ParamObj = Required<{\n [Prop in keyof Props]: unknown\n}>\nexport function getErrors({ items, itemShapes }: ParamObj) {",
"score": 14.81613146197215
},
{
"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": 11.343369107281406
},
{
"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": 11.030824051751852
},
{
"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": 9.00092751481997
}
] | 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": " hasHF: false,\n testId: getSvgTestIds(starIndex),\n }\n if (deservesHF && absoluteHFMode === HFProps.SVG) {\n sharedProps.hasHF = starIndex === activeStarIndex\n }\n return sharedProps\n }\n /* Render */\n return (",
"score": 10.854023687169889
},
{
"filename": "src/getGroupClassNames.ts",
"retrieved_chunk": " !readOnly && isDisabled ? CursorClasses.DISABLED : ''\n const transitionClassName =\n isDynamic && transition !== TransitionProps.NONE ? getTransitionClassNames(transition) : ''\n const orientationClassName: CSSClassName =\n orientation === OrientationProps.VERTICAL\n ? OrientationClasses.VERTICAL\n : OrientationClasses.HORIZONTAL\n const radiusClassName = getRadiusClassName(radius)\n const borderClassName: MaybeEmptyClassName = absoluteBoxBorderWidth > 0 ? HasClasses.BORDER : ''\n const strokeClassName: MaybeEmptyClassName = absoluteStrokeWidth > 0 ? HasClasses.STROKE : ''",
"score": 9.763359972107121
},
{
"filename": "src/Rating.tsx",
"retrieved_chunk": " const [tabIndex, setTabIndex] = useState<TabIndex[]>(() => {\n if (isDynamic) {\n return getTabIndex(tabIndexItems, activeStarIndex, !isRequired)\n }\n return []\n })\n /* Effects */\n useIsomorphicLayoutEffect(() => {\n if (isDynamic && radioRefs.current) {\n isRTL.current = isRTLDir(radioRefs.current[0])",
"score": 9.08617649612118
},
{
"filename": "src/internalTypes.ts",
"retrieved_chunk": " itemStrokeWidth: NonNullable<ItemStyles['itemStrokeWidth']>\n orientation: NonNullProp<'orientation'>\n hasHF: boolean\n testId?: object\n}\nexport type StylesState = {\n staticCssVars: CSSVariables\n dynamicCssVars: CSSVariables[]\n dynamicClassNames: CSSClassName[]\n}",
"score": 8.914434169161009
},
{
"filename": "src/Rating.tsx",
"retrieved_chunk": " }\n }\n function pushGroupRefs(element: HTMLDivElement) {\n if (isDynamic && !isRequired) {\n ;(wrapperRef as MutableRef).current = element\n }\n if (externalRef) {\n ;(externalRef as MutableRef).current = element\n }\n }",
"score": 8.572078357572778
}
] | 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": 25.810639121238875
},
{
"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": 22.150434959874655
},
{
"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": 20.02277983020862
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": "};\nexport type Controller = (\n event: APIGatewayProxyEventV2\n) =>\n | APIGatewayProxyStructuredResultV2\n | Promise<APIGatewayProxyStructuredResultV2>;\nexport const routes: Array<Route> = [\n {\n method: \"GET\",\n path: \"/info/events\",",
"score": 19.218928097624747
},
{
"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": 19.127268687670423
}
] | 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": 34.68305370555858
},
{
"filename": "src/getHFClassNames.ts",
"retrieved_chunk": " if (absoluteHFMode === 'box') {\n if (index > intersectionIndex) {\n return HFClasses.BOX_OFF\n }\n if (index === intersectionIndex) {\n return HFClasses.BOX_INT\n }\n return HFClasses.BOX_ON\n }\n if (index > intersectionIndex) {",
"score": 25.626075235659332
},
{
"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": 15.180916049821702
},
{
"filename": "src/getHFClassNames.ts",
"retrieved_chunk": " return HFClasses.SVG_OFF\n }\n return HFClasses.SVG_ON\n })\n}",
"score": 13.82442762037621
},
{
"filename": "src/exportedTypes.ts",
"retrieved_chunk": " /** Active stroke color of the SVG, it can be an array of colors in ascending order. */\n activeStrokeColor?: string | string[]\n /** Active background color of the SVG bounding box, it can be an array of colors in ascending order. */\n activeBoxColor?: string | string[]\n /** Active border color of the SVG bounding box, it can be an array of colors in ascending order. */\n activeBoxBorderColor?: string | string[]\n}\nexport type NonArrayColors = {\n /** Inactive fill color of the SVG. */\n inactiveFillColor?: string",
"score": 13.100429973917462
}
] | 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": 28.44294989475519
},
{
"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": 25.06157178845559
},
{
"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": 24.260912270655847
},
{
"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": 23.888135423605018
},
{
"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": 21.263609497494322
}
] | 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/utils.ts",
"retrieved_chunk": "export const getUniqueId = () => (Math.random() + 1).toString(36).substring(7)\nexport const areNum = (...values: unknown[]) => values.every((value) => typeof value === 'number')\nexport const getNewPosition = (originalPos: number) =>\n originalPos === 0 ? 0 : toSecondDecimal(originalPos) * -1\nexport const isGraphicalValueInteger = (ratingValue: number) =>\n Number.isInteger(roundToHalf(ratingValue))\nexport function getIntersectionIndex(ratingValues: number[], ratingValue: number) {\n const roundedHalf = roundToHalf(ratingValue)\n if (Number.isInteger(roundedHalf)) {\n return ratingValues.indexOf(roundedHalf)",
"score": 28.952006747738057
},
{
"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": 12.004459186085718
},
{
"filename": "src/getHFClassNames.ts",
"retrieved_chunk": "import { roundToHalf } from './utils'\nimport { NonNullProp, CSSClassName } from './internalTypes'\nimport { HFClasses } from './constants'\nexport function getHFClassNames(\n ratingValue: NonNullProp<'value'>,\n items: NonNullProp<'items'>,\n absoluteHFMode: NonNullProp<'halfFillMode'>\n): CSSClassName[] {\n const intersectionIndex = Math.floor(roundToHalf(ratingValue))\n return Array.from({ length: items }, (_, index) => {",
"score": 11.204955417773478
},
{
"filename": "src/getColors.ts",
"retrieved_chunk": " }\n }\n return { arrayColors, staticColors: allColors as StaticColors }\n}",
"score": 10.67914924985571
},
{
"filename": "src/RatingItem.tsx",
"retrieved_chunk": " viewBox,\n translateData,\n })\n }\n }\n }, [itemShapes, itemStrokeWidth, hasHF])\n /* Props */\n function getHFAttr() {\n if (hasHF) {\n return {",
"score": 10.464469006085343
}
] | 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/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": 13.74003518856373
},
{
"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": 13.20411323006367
},
{
"filename": "src/api/index.ts",
"retrieved_chunk": " };\n }\n const path = event.requestContext.http.path;\n const method = event.requestContext.http.method.toUpperCase();\n let controller = undefined as undefined | Controller;\n for (const route of routes) {\n if (method === route.method && new RegExp(`^${route.path}$`).test(path)) {\n controller = route.controller;\n break;\n }",
"score": 11.97152116138619
},
{
"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": 11.866210337055715
},
{
"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": 11.78580182263089
}
] | 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/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": 48.7876973555614
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": " controller: chaptersController,\n },\n {\n method: \"GET\",\n path: \"/info/chapter-icons/[A-Za-z-]+\",\n controller: chapterIconController,\n },\n {\n method: \"GET\",\n path: \"/info/health\",",
"score": 46.07061473413302
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": "import { APIGatewayProxyEventV2 } from \"aws-lambda\";\nimport { APIGatewayProxyStructuredResultV2 } from \"aws-lambda/trigger/api-gateway-proxy\";\nimport { chaptersController } from \"./controllers/chapters.controller\";\nimport { chapterIconController } from \"./controllers/chapter-icon.controller\";\nimport { healthController } from \"./controllers/health.controller\";\nimport { notifyController } from \"./controllers/notify.controller\";\ntype Route = {\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n path: string;\n controller: Controller;",
"score": 38.006665542817544
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": "};\nexport type Controller = (\n event: APIGatewayProxyEventV2\n) =>\n | APIGatewayProxyStructuredResultV2\n | Promise<APIGatewayProxyStructuredResultV2>;\nexport const routes: Array<Route> = [\n {\n method: \"GET\",\n path: \"/info/events\",",
"score": 30.296596512351545
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": " controller: notifyController,\n },\n];",
"score": 26.948838500238644
}
] | 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": 32.56540796296372
},
{
"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": 15.398270487248974
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": " border-radius: 2px;\n width: 30px;\n height: 30px;\n display: none;\n @media (max-width: 600px) {\n display: block;\n }\n`;\nconst InfoContainer = styled.div`\n display: flex;",
"score": 7.397871626260017
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": " margin: 0;\n font-size: 15px;\n color: #6c6c6c;\n padding-left: 4px;\n`;\nconst EventImage = styled.img`\n max-width: 111px;\n max-height: 74px;\n border-radius: 5px;\n`;",
"score": 7.123555325029254
},
{
"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": 6.519216828233008
}
] | 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/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": 14.439387046436451
},
{
"filename": "src/ui/calendar/events.util.ts",
"retrieved_chunk": " result.totalRSVPs += event.going;\n if (!chapters.has(event.group.urlname)) {\n result.totalActiveChapters++;\n chapters.add(event.group.urlname);\n }\n });\n return result;\n}",
"score": 13.846414715237405
},
{
"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": 11.35259466652989
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": " controller: chaptersController,\n },\n {\n method: \"GET\",\n path: \"/info/chapter-icons/[A-Za-z-]+\",\n controller: chapterIconController,\n },\n {\n method: \"GET\",\n path: \"/info/health\",",
"score": 10.537417779393653
},
{
"filename": "src/ui/web-conf.ts",
"retrieved_chunk": "export const WebConf = {\n smBreakpoint: 600,\n rootHost: import.meta.env.VITE_ROOT_URL,\n};",
"score": 9.725427790950656
}
] | typescript | }/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/api/dao/meetup.dao.ts",
"retrieved_chunk": " group: {\n id: string;\n name: string;\n city: string;\n state: string;\n urlname: string;\n };\n description: string;\n};\n/**",
"score": 13.58812943499215
},
{
"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": 11.669981854508018
},
{
"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": 10.738334325558128
},
{
"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": 8.516407943373732
},
{
"filename": "src/api/index.ts",
"retrieved_chunk": " };\n }\n const path = event.requestContext.http.path;\n const method = event.requestContext.http.method.toUpperCase();\n let controller = undefined as undefined | Controller;\n for (const route of routes) {\n if (method === route.method && new RegExp(`^${route.path}$`).test(path)) {\n controller = route.controller;\n break;\n }",
"score": 8.130494291832271
}
] | 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": "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": 65.5590004288369
},
{
"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": 59.669861986795226
},
{
"filename": "src/component.ts",
"retrieved_chunk": "import type { AsString, IsFiniteString, Merge, Prod } from \"./utils\";\n/**\n * `Component<N, T>` represents a component.\n * @param N The name of the component.\n * @param T The type of the component instance.\n */\nexport type Component<N extends string, T extends unknown> = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __type: \"hokemi.type.Component\";\n name: N;",
"score": 44.27174091123233
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 30.508670320594423
},
{
"filename": "src/component.ts",
"retrieved_chunk": " * @param Cs Components.\n */\nexport type Mixed<Cs extends AbstractComponent[]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;\n// prettier-ignore\ntype FilteredInstances<\n Cs extends AbstractComponent[],\n Is extends Array<{}>,\n K extends string\n> = Cs extends [] ? Is\n : Cs extends [",
"score": 29.728518917144143
}
] | typescript | <infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never; |
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": "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": 65.5590004288369
},
{
"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": 59.669861986795226
},
{
"filename": "src/component.ts",
"retrieved_chunk": "import type { AsString, IsFiniteString, Merge, Prod } from \"./utils\";\n/**\n * `Component<N, T>` represents a component.\n * @param N The name of the component.\n * @param T The type of the component instance.\n */\nexport type Component<N extends string, T extends unknown> = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __type: \"hokemi.type.Component\";\n name: N;",
"score": 44.27174091123233
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 30.508670320594423
},
{
"filename": "src/component.ts",
"retrieved_chunk": " * @param Cs Components.\n */\nexport type Mixed<Cs extends AbstractComponent[]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;\n// prettier-ignore\ntype FilteredInstances<\n Cs extends AbstractComponent[],\n Is extends Array<{}>,\n K extends string\n> = Cs extends [] ? Is\n : Cs extends [",
"score": 29.728518917144143
}
] | typescript | > = C extends Component<infer N, infer T> ? Provider<N, T, Mixed<Ds>> : never; |
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": "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": 46.55571248171532
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 43.30826712667989
},
{
"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": 42.483197418548656
},
{
"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": 34.87727870978378
},
{
"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": 34.7947969613249
}
] | typescript | export type MixedProvidedInstance<Ps extends AbstractProvider[]> = Mixed<{ |
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": 32.56540796296372
},
{
"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": 15.398270487248974
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": " border-radius: 2px;\n width: 30px;\n height: 30px;\n display: none;\n @media (max-width: 600px) {\n display: block;\n }\n`;\nconst InfoContainer = styled.div`\n display: flex;",
"score": 7.397871626260017
},
{
"filename": "src/ui/calendar/coffee-event.tsx",
"retrieved_chunk": " margin: 0;\n font-size: 15px;\n color: #6c6c6c;\n padding-left: 4px;\n`;\nconst EventImage = styled.img`\n max-width: 111px;\n max-height: 74px;\n border-radius: 5px;\n`;",
"score": 7.123555325029254
},
{
"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": 6.519216828233008
}
] | typescript | <CoffeeEventStats stats={stats} />} |
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": 34.27408240600145
},
{
"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": 19.64101206452914
},
{
"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": 19.24876847358413
},
{
"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": 18.303467492356024
},
{
"filename": "src/component.spec.ts",
"retrieved_chunk": " assertType<Equals<Instance<XxxComponent>, never>>();\n type FooComponent = Component<\"foo1\" | \"foo2\", { getFoo: () => number }>;\n assertType<\n Equals<\n Instance<FooComponent>,\n Readonly<{ foo1: { getFoo: () => number } }> | Readonly<{ foo2: { getFoo: () => number } }>\n >\n >();\n });\n it(\"returns an object type with an optional index signature if the component name is not of a finite string type\", () => {",
"score": 17.78892498103172
}
] | 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": 60.49982639344943
},
{
"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": 37.952226633701805
},
{
"filename": "src/api/index.ts",
"retrieved_chunk": " };\n }\n const path = event.requestContext.http.path;\n const method = event.requestContext.http.method.toUpperCase();\n let controller = undefined as undefined | Controller;\n for (const route of routes) {\n if (method === route.method && new RegExp(`^${route.path}$`).test(path)) {\n controller = route.controller;\n break;\n }",
"score": 35.785918751168104
},
{
"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": 21.953034876891234
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": "};\nexport type Controller = (\n event: APIGatewayProxyEventV2\n) =>\n | APIGatewayProxyStructuredResultV2\n | Promise<APIGatewayProxyStructuredResultV2>;\nexport const routes: Array<Route> = [\n {\n method: \"GET\",\n path: \"/info/events\",",
"score": 21.469703021229503
}
] | typescript | <CoffeeEvent event={event} key={event.id} />); |
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/events.util.ts",
"retrieved_chunk": " result.totalRSVPs += event.going;\n if (!chapters.has(event.group.urlname)) {\n result.totalActiveChapters++;\n chapters.add(event.group.urlname);\n }\n });\n return result;\n}",
"score": 20.76962207285611
},
{
"filename": "src/api/dao/meetup.dao.ts",
"retrieved_chunk": " group: {\n id: string;\n name: string;\n city: string;\n state: string;\n urlname: string;\n };\n description: string;\n};\n/**",
"score": 15.329167330290826
},
{
"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": 15.056012403680448
},
{
"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": 12.272659769611582
},
{
"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": 11.389891799341083
}
] | typescript | const date = new Date(event.dateTime); |
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": 23.96418192334142
},
{
"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": 20.63205572640442
},
{
"filename": "src/component.ts",
"retrieved_chunk": " * @param Cs Components.\n */\nexport type Mixed<Cs extends AbstractComponent[]> = Merge<Prod<FilteredInstances<Cs, [], never>>>;\n// prettier-ignore\ntype FilteredInstances<\n Cs extends AbstractComponent[],\n Is extends Array<{}>,\n K extends string\n> = Cs extends [] ? Is\n : Cs extends [",
"score": 12.45288335287523
},
{
"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": 12.26062719720035
},
{
"filename": "src/component.ts",
"retrieved_chunk": "import type { AsString, IsFiniteString, Merge, Prod } from \"./utils\";\n/**\n * `Component<N, T>` represents a component.\n * @param N The name of the component.\n * @param T The type of the component instance.\n */\nexport type Component<N extends string, T extends unknown> = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __type: \"hokemi.type.Component\";\n name: N;",
"score": 11.42220810434522
}
] | typescript | assertType<Equals<Merge<{}>, {}>>(); |
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": "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": 37.36139789220954
},
{
"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": 37.18812033773306
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 34.71370518195446
},
{
"filename": "src/mixer.ts",
"retrieved_chunk": " [N in keyof D]: N extends keyof I\n ? never\n : {\n name: N;\n expectedType: D[N];\n };\n }[keyof D]\n >\n : never;\ntype IncompatibleDependenciesError<",
"score": 30.361238858750617
},
{
"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": 29.02067324317823
}
] | typescript | Merge<Prod<FilteredInstances<Cs, [], never>>>; |
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": "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": 46.55571248171532
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 43.30826712667989
},
{
"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": 38.11200084766023
},
{
"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": 34.87727870978378
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "export type Wrap<T> = [T] extends [never] ? never : [T];",
"score": 32.04530352487176
}
] | typescript | ]> = Mixed<{ |
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": 60.49982639344943
},
{
"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": 37.952226633701805
},
{
"filename": "src/api/index.ts",
"retrieved_chunk": " };\n }\n const path = event.requestContext.http.path;\n const method = event.requestContext.http.method.toUpperCase();\n let controller = undefined as undefined | Controller;\n for (const route of routes) {\n if (method === route.method && new RegExp(`^${route.path}$`).test(path)) {\n controller = route.controller;\n break;\n }",
"score": 35.785918751168104
},
{
"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": 21.953034876891234
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": "};\nexport type Controller = (\n event: APIGatewayProxyEventV2\n) =>\n | APIGatewayProxyStructuredResultV2\n | Promise<APIGatewayProxyStructuredResultV2>;\nexport const routes: Array<Route> = [\n {\n method: \"GET\",\n path: \"/info/events\",",
"score": 21.469703021229503
}
] | typescript | push(<CoffeeEvent event={event} key={event.id} />); |
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/meetup.dao.ts",
"retrieved_chunk": " title: string;\n going: number;\n imageUrl: string;\n venue: {\n name: string;\n address: string;\n city: string;\n state: string;\n } | null;\n dateTime: string;",
"score": 18.197760237114228
},
{
"filename": "src/ui/calendar/events.util.ts",
"retrieved_chunk": " result.totalRSVPs += event.going;\n if (!chapters.has(event.group.urlname)) {\n result.totalActiveChapters++;\n chapters.add(event.group.urlname);\n }\n });\n return result;\n}",
"score": 14.049142143432544
},
{
"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": 13.690603835747709
},
{
"filename": "src/api/dao/meetup.dao.ts",
"retrieved_chunk": " group: {\n id: string;\n name: string;\n city: string;\n state: string;\n urlname: string;\n };\n description: string;\n};\n/**",
"score": 11.917175390061814
},
{
"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": 10.794842491631902
}
] | 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.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": 14.439387046436451
},
{
"filename": "src/ui/calendar/events.util.ts",
"retrieved_chunk": " result.totalRSVPs += event.going;\n if (!chapters.has(event.group.urlname)) {\n result.totalActiveChapters++;\n chapters.add(event.group.urlname);\n }\n });\n return result;\n}",
"score": 13.846414715237405
},
{
"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": 11.35259466652989
},
{
"filename": "src/api/routes.ts",
"retrieved_chunk": " controller: chaptersController,\n },\n {\n method: \"GET\",\n path: \"/info/chapter-icons/[A-Za-z-]+\",\n controller: chapterIconController,\n },\n {\n method: \"GET\",\n path: \"/info/health\",",
"score": 10.537417779393653
},
{
"filename": "src/ui/web-conf.ts",
"retrieved_chunk": "export const WebConf = {\n smBreakpoint: 600,\n rootHost: import.meta.env.VITE_ROOT_URL,\n};",
"score": 9.725427790950656
}
] | 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": " 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": 39.25573912277136
},
{
"filename": "src/api/index.ts",
"retrieved_chunk": " };\n }\n const path = event.requestContext.http.path;\n const method = event.requestContext.http.method.toUpperCase();\n let controller = undefined as undefined | Controller;\n for (const route of routes) {\n if (method === route.method && new RegExp(`^${route.path}$`).test(path)) {\n controller = route.controller;\n break;\n }",
"score": 29.304445432684282
},
{
"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": 20.463965034918814
},
{
"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": 17.923620962195102
},
{
"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": 16.997522267818457
}
] | typescript | window.open(event.eventUrl, "_blank"); |
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": " >();\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": 18.256674855133635
},
{
"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": 17.84319170425318
},
{
"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": 16.24045656873219
},
{
"filename": "src/provider.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 Impl<FooComponent | BarComponent, [BazComponent]>,\n | Provider<\"foo\", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>\n | Provider<\"bar\", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>\n >\n >();",
"score": 15.809411118168002
},
{
"filename": "src/mixer.spec.ts",
"retrieved_chunk": " const m = mixer(foo, bar, baz);\n assertType<Equals<typeof m, Mixer<[typeof foo, typeof bar, typeof baz]>>>();\n const mixed = m.new();\n assertType<Equals<typeof mixed, Mixed<[FooComponent, BarComponent, BazComponent]>>>();\n expect(mixed.foo.getFoo()).toBe(5);\n });\n it(\"overrides previous mixed components\", () => {\n const foo = impl<FooComponent, [BarComponent, BazComponent]>(\"foo\", ({ bar, baz }) => ({\n getFoo: () => (baz.getBaz() ? bar.getBar().length : 42),\n }));",
"score": 14.534743664798345
}
] | typescript | Mixed<[]>, {}>>(); |
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": 37.80139008231792
},
{
"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": 34.381482702803616
},
{
"filename": "src/provider.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 Impl<FooComponent | BarComponent, [BazComponent]>,\n | Provider<\"foo\", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>\n | Provider<\"bar\", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>\n >\n >();",
"score": 32.30959911313777
},
{
"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": 31.664069461520747
},
{
"filename": "src/component.spec.ts",
"retrieved_chunk": " Mixed<[FooComponent, BarComponent] | [BazComponent]>,\n | Readonly<{\n foo: { getFoo: () => number };\n bar: { getBar: () => string };\n }>\n | Readonly<{\n baz: { getBaz: () => boolean };\n }>\n >\n >();",
"score": 29.564453330263532
}
] | typescript | const m = mixer(foo, bar, baz); |
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": "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": 46.55571248171532
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 43.30826712667989
},
{
"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": 38.11200084766023
},
{
"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": 34.87727870978378
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "export type Wrap<T> = [T] extends [never] ? never : [T];",
"score": 32.04530352487176
}
] | 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": "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": 37.36139789220954
},
{
"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": 37.18812033773306
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " )\n : never;\nexport type AsString<T> = T extends string ? T : never;\nexport type Prod<Xs extends unknown[]> = Xs extends unknown\n ? { [K in keyof Xs]: (x: Xs[K]) => unknown }[number] extends (x: infer P) => unknown\n ? P\n : never\n : never;\nexport type Merge<T> = { [K in keyof T]: T[K] };\nexport type OrElse<T, E> = [T] extends [never] ? E : T;",
"score": 34.71370518195446
},
{
"filename": "src/mixer.ts",
"retrieved_chunk": " [N in keyof D]: N extends keyof I\n ? never\n : {\n name: N;\n expectedType: D[N];\n };\n }[keyof D]\n >\n : never;\ntype IncompatibleDependenciesError<",
"score": 30.361238858750617
},
{
"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": 29.02067324317823
}
] | 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": " 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": 34.167073762565124
},
{
"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": 33.96234483556
},
{
"filename": "src/provider.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 Impl<FooComponent | BarComponent, [BazComponent]>,\n | Provider<\"foo\", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>\n | Provider<\"bar\", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>\n >\n >();",
"score": 33.249126566809565
},
{
"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": 32.537756053032304
},
{
"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": 31.309115240431762
}
] | 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/mixer.ts",
"retrieved_chunk": " const instances = new Map<string, unknown>();\n const getters = new Map<string, () => unknown>();\n const lock = new Set<string>();\n for (const { name, factory } of providers) {\n const getter = (): unknown => {\n if (instances.has(name)) {\n return instances.get(name);\n }\n if (lock.has(name)) {\n throw new Error(`'${name}' is referenced during its initialization`);",
"score": 64.77812716275042
},
{
"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": 36.893146771033905
},
{
"filename": "src/provider.ts",
"retrieved_chunk": " deps: D\n): T {\n // check if the factory is a class (not a perfect check though)\n const desc = Object.getOwnPropertyDescriptor(factory, \"prototype\");\n if (desc && !desc.writable) {\n // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion\n return new (factory as FactoryClass<T, D>)(deps);\n } else {\n // eslint-disable-next-line @susisu/safe-typescript/no-type-assertion\n return (factory as FactoryFunction<T, D>)(deps);",
"score": 32.279616311667944
},
{
"filename": "src/provider.spec.ts",
"retrieved_chunk": " expect(value.getFoo()).toBe(42);\n });\n it(\"calls the constructor of the argument if it is a class\", () => {\n const factory = class Foo {\n private foo: number;\n constructor(foo: number) {\n this.foo = foo;\n }\n getFoo(): number {\n return this.foo;",
"score": 30.90370642285941
},
{
"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": 30.370486017554402
}
] | 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": 24.283044896940503
},
{
"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": 18.89655093585021
},
{
"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": 18.635305623200964
},
{
"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": 18.524407315507556
},
{
"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": 18.429252714450246
}
] | 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": " 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": 34.167073762565124
},
{
"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": 33.96234483556
},
{
"filename": "src/provider.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 Impl<FooComponent | BarComponent, [BazComponent]>,\n | Provider<\"foo\", { getFoo: () => number }, Readonly<{ baz: { getBaz: () => boolean } }>>\n | Provider<\"bar\", { getBar: () => string }, Readonly<{ baz: { getBaz: () => boolean } }>>\n >\n >();",
"score": 33.249126566809565
},
{
"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": 32.537756053032304
},
{
"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": 31.309115240431762
}
] | typescript | const foo = impl<FooComponent, [BarComponent, BazComponent]>("foo", ({ bar, baz }) => ({ |
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": 34.27408240600145
},
{
"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": 19.64101206452914
},
{
"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": 19.24876847358413
},
{
"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": 18.303467492356024
},
{
"filename": "src/component.spec.ts",
"retrieved_chunk": " assertType<Equals<Instance<XxxComponent>, never>>();\n type FooComponent = Component<\"foo1\" | \"foo2\", { getFoo: () => number }>;\n assertType<\n Equals<\n Instance<FooComponent>,\n Readonly<{ foo1: { getFoo: () => number } }> | Readonly<{ foo2: { getFoo: () => number } }>\n >\n >();\n });\n it(\"returns an object type with an optional index signature if the component name is not of a finite string type\", () => {",
"score": 17.78892498103172
}
] | typescript | <OrElse<never, "xxx">, "xxx">>(); |
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": 20.465985373299354
},
{
"filename": "src/logger.ts",
"retrieved_chunk": " let msg = ''\n let split = string.split('§')\n msg += split[0]\n for (let a of string.split('§').slice(1, split.length)) {\n let color = a.charAt(0)\n let message\n if (Object.keys(colors).includes(color)) {\n msg += colors[color]\n }\n message = a.substring(1, a.length)",
"score": 19.39936149549212
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " var parts = number.toString().split('.')\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n return parts.join('.')\n}\nexport function isCoflChatMessage(message: string) {\n return removeMinecraftColorCodes(message).startsWith('[Chat]')\n}\nexport function removeMinecraftColorCodes(text: string) {\n return text?.replace(/§[0-9a-fk-or]/gi, '')\n}",
"score": 18.043881580955073
},
{
"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": 16.28214582723124
},
{
"filename": "src/ingameMessageHandler.ts",
"retrieved_chunk": " text.split(' bought ')[1].split(' for ')[0],\n text.split(' for ')[1].split(' coins')[0],\n text.split('[Auction] ')[1].split(' bought ')[0]\n )\n }\n if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) {\n wss.send(\n JSON.stringify({\n type: 'chatBatch',\n data: JSON.stringify([text])",
"score": 15.879476619201476
}
] | typescript | let isCoflChat = isCoflChatMessage(da.text)
if (!isCoflChat) { |
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": 22.984242763888957
},
{
"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": 20.024772364891167
},
{
"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": 15.312668657819163
},
{
"filename": "src/ingameMessageHandler.ts",
"retrieved_chunk": " text.split(' bought ')[1].split(' for ')[0],\n text.split(' for ')[1].split(' coins')[0],\n text.split('[Auction] ')[1].split(' bought ')[0]\n )\n }\n if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) {\n wss.send(\n JSON.stringify({\n type: 'chatBatch',\n data: JSON.stringify([text])",
"score": 12.949548753144589
},
{
"filename": "src/configHelper.ts",
"retrieved_chunk": " USE_COFL_CHAT: true,\n SESSIONS: {},\n USE_WINDOW_SKIPS: false\n}\njson2toml({ simple: true })\nexport function initConfigHelper() {\n if (fs.existsSync(filePath)) {\n let existingConfig = toml.parse(fs.readFileSync(filePath, { encoding: 'utf8', flag: 'r' }))\n // add new default values to existing config if new property was added in newer version\n let hadChange = false",
"score": 11.225248065630522
}
] | typescript | = 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/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": 34.11553522313673
},
{
"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": 26.689120384596475
},
{
"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": 26.010031187407158
},
{
"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": 23.94076977239372
},
{
"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": 21.458124216722606
}
] | 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/logger.ts",
"retrieved_chunk": " let msg = ''\n let split = string.split('§')\n msg += split[0]\n for (let a of string.split('§').slice(1, split.length)) {\n let color = a.charAt(0)\n let message\n if (Object.keys(colors).includes(color)) {\n msg += colors[color]\n }\n message = a.substring(1, a.length)",
"score": 32.25223922764982
},
{
"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": 23.312046655996117
},
{
"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": 23.065456158003908
},
{
"filename": "src/logger.ts",
"retrieved_chunk": " msg += message\n }\n console.log('\\x1b[0m\\x1b[1m\\x1b[90m' + msg + '\\x1b[0m')\n}\n// this function adds a logging function to the wrtie function of the client\n// resulting in all sent packets being logged by the logPacket function\nexport function addLoggerToClientWriteFunction(client: Client) {\n ;(function () {\n var old_prototype = client.write.prototype\n var old_init = client.write",
"score": 19.93524386300698
},
{
"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": 18.34791158970587
}
] | typescript | for (let da of [...(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/logger.ts",
"retrieved_chunk": " let msg = ''\n let split = string.split('§')\n msg += split[0]\n for (let a of string.split('§').slice(1, split.length)) {\n let color = a.charAt(0)\n let message\n if (Object.keys(colors).includes(color)) {\n msg += colors[color]\n }\n message = a.substring(1, a.length)",
"score": 27.349851649501133
},
{
"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": 22.896650783985116
},
{
"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": 20.2883100931667
},
{
"filename": "src/tradeHandler.ts",
"retrieved_chunk": " })\n clickWindow(bot, 36)\n }\n if (!(data.coins > 0) || addedCoins) {\n websocket.send(JSON.stringify({ type: 'affirmFlip', data: [JSON.stringify(window.slots)] }))\n }\n })\n }\n })\n await sleep(5000)",
"score": 17.25748828379169
},
{
"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": 16.596272539362033
}
] | typescript | (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/logger.ts",
"retrieved_chunk": " let msg = ''\n let split = string.split('§')\n msg += split[0]\n for (let a of string.split('§').slice(1, split.length)) {\n let color = a.charAt(0)\n let message\n if (Object.keys(colors).includes(color)) {\n msg += colors[color]\n }\n message = a.substring(1, a.length)",
"score": 68.98019677643636
},
{
"filename": "src/sellHandler.ts",
"retrieved_chunk": " log('Price not present', 'error')\n log(sellWindow.slots[29])\n resetAndTakeOutItem()\n return\n }\n if (priceLine.startsWith('{')) {\n let obj = JSON.parse(priceLine)\n priceLine = obj.extra[1].text.replace(/[,.]/g, '').split(' coins')[0]\n } else {\n priceLine = removeMinecraftColorCodes(priceLine)",
"score": 55.55593577145157
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " var parts = number.toString().split('.')\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n return parts.join('.')\n}\nexport function isCoflChatMessage(message: string) {\n return removeMinecraftColorCodes(message).startsWith('[Chat]')\n}\nexport function removeMinecraftColorCodes(text: string) {\n return text?.replace(/§[0-9a-fk-or]/gi, '')\n}",
"score": 52.37491830190846
},
{
"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": 44.25888605390572
},
{
"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": 35.69222516910382
}
] | typescript | if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) { |
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": "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": 65.49336395564495
},
{
"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": 41.22638553628722
},
{
"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": 37.95751363464067
},
{
"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": 35.21621340102179
},
{
"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": 32.6399084143764
}
] | typescript | bot.removeAllListeners('windowOpen')
bot.state = null
return
} |
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": 22.58768800179684
},
{
"filename": "src/ingameMessageHandler.ts",
"retrieved_chunk": " if (item?.nbt?.value?.display?.value?.Lore && JSON.stringify(item.nbt.value.display.value.Lore).includes('Sold for')) {\n clickSlot = item.slot\n }\n if (item && item.type === 380 && (item.nbt as any).value?.display?.value?.Name?.value?.toString().includes('Claim All')) {\n log(item)\n log('Found cauldron to claim all sold auctions -> clicking index ' + item.slot)\n clickWindow(bot, item.slot)\n clearTimeout(timeout)\n bot.removeAllListeners('windowOpen')\n bot.state = null",
"score": 21.39834639856965
},
{
"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": 21.214088108977148
},
{
"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": 20.70440738646161
},
{
"filename": "src/ingameMessageHandler.ts",
"retrieved_chunk": " let name = (slot?.nbt as any)?.value?.display?.value?.Name?.value?.toString()\n if (slot?.type === 380 && name?.includes('Claim') && name?.includes('All')) {\n log('Found cauldron to claim all purchased auctions -> clicking index ' + i)\n clickWindow(bot, i)\n bot.removeAllListeners('windowOpen')\n bot.state = null\n return\n }\n let lore = (slot?.nbt as any)?.value?.display?.value?.Lore?.value?.value?.toString()\n if (lore?.includes('Status:') && lore?.includes('Sold!')) {",
"score": 20.641228657516077
}
] | typescript | if (data.coins > 0 && !addedCoins) { |
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": 23.097953271810564
},
{
"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": 20.15772076590619
},
{
"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": 15.435365386710139
},
{
"filename": "src/ingameMessageHandler.ts",
"retrieved_chunk": " text.split(' bought ')[1].split(' for ')[0],\n text.split(' for ')[1].split(' coins')[0],\n text.split('[Auction] ')[1].split(' bought ')[0]\n )\n }\n if (bot.privacySettings && bot.privacySettings.chatRegex.test(text)) {\n wss.send(\n JSON.stringify({\n type: 'chatBatch',\n data: JSON.stringify([text])",
"score": 13.073838668939024
},
{
"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": 12.068697458528975
}
] | 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/sellHandler.ts",
"retrieved_chunk": "import { MyBot, SellData } from '../types/autobuy'\nimport { log, printMcChatToConsole } from './logger'\nimport { clickWindow, getWindowTitle, numberWithThousandsSeparators, removeMinecraftColorCodes } from './utils'\nimport { sendWebhookItemListed } from './webhookHandler'\nlet setPrice = false\nlet durationSet = false\nlet retryCount = 0\nexport async function onWebsocketCreateAuction(bot: MyBot, data: SellData) {\n if (bot.state) {\n log('Currently busy with something else (' + bot.state + ') -> not selling')",
"score": 25.061719378926373
},
{
"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": 20.235666299930198
},
{
"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": 20.04499889765688
},
{
"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": 14.545061628440735
},
{
"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": 14.230765731285008
}
] | typescript | bot.chat('/ah')
setTimeout(() => { |
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": " equals(item: Item): boolean {\n return this._id === item.id;\n }\n}",
"score": 39.744602743431585
},
{
"filename": "src/app/entities/item/Item.spec.ts",
"retrieved_chunk": " name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n });\n expect(item.equals(item2)).toBeTruthy();\n });\n it(\"should not be equals\", () => {\n const item2 = new Item({",
"score": 38.87933388521526
},
{
"filename": "src/app/entities/item/Item.spec.ts",
"retrieved_chunk": " id: \"2\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n });\n expect(item.equals(item2)).toBeFalsy();\n });\n});",
"score": 37.90186111923872
},
{
"filename": "src/app/use-cases/pokemon/AddPokemonUseCase.spec.ts",
"retrieved_chunk": " for (let i = 0; i < 3; i++) {\n await addPokemonUseCase.execute({\n name: \"Pikachu\",\n level: 25,\n life: 100,\n type: [\"electric\"],\n stats: new BattleStats({\n attack: 10,\n defense: 10,\n speed: 10,",
"score": 35.94562760337586
},
{
"filename": "src/app/entities/item/Item.spec.ts",
"retrieved_chunk": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport { Item } from \"./Item\";\ndescribe(\"Item\", () => {\n let item: Item;\n beforeEach(() => {\n item = new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,",
"score": 35.90530560109885
}
] | 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/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": 20.702381947449208
},
{
"filename": "src/app/entities/pokemon/Pokemon.spec.ts",
"retrieved_chunk": " });\n it(\"should attack\", () => {\n pikachu.attack(charmander);\n const expectedDamage = pikachu.stats.attack - charmander.stats.defense;\n expect(charmander.life).toBe(100 - expectedDamage);\n });\n it(\"should be awake\", () => {\n expect(pikachu.isAwake()).toBeTruthy();\n });\n it(\"should be asleep\", () => {",
"score": 19.47716480053223
},
{
"filename": "src/app/use-cases/battle/CreateBattleUseCase.spec.ts",
"retrieved_chunk": " trainerID: trainer1.id,\n life: 100,\n moves: [],\n stats: new BattleStats({\n attack: 100,\n defense: 100,\n speed: 100,\n }),\n })\n );",
"score": 16.98363452616504
},
{
"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": 16.664109123956038
},
{
"filename": "src/app/entities/pokemon/Pokemon.spec.ts",
"retrieved_chunk": " stats: new BattleStats({\n attack: 100,\n defense: 100,\n speed: 100,\n }),\n level: 25,\n life: 100,\n moves: [\n new PokemonMove({\n name: \"Thunderbolt\",",
"score": 15.93517726798422
}
] | typescript | = this._stats.attack - target.stats.defense; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.