import type { Result, Success, Failure } from '@expo/results'; /** * Enforce an array of results resolved from supplied promise. * @param resultsPromise - promise returning an array of results to enforce */ export const enforceResultsAsync = async ( resultsPromise: Promise[]>, ): Promise => { const results = await resultsPromise; return results.map((result) => result.enforceValue()); }; /** * Filter out unsuccessful results. * @param results - array of results to filter */ export const successfulResults = (results: readonly Result[]): readonly Success[] => { const ret: Success[] = []; for (const result of results) { if (result.ok) { ret.push(result); } } return ret; }; /** * Filter out successful results. * @param results - array of results to filter */ export const failedResults = (results: readonly Result[]): readonly Failure[] => { const ret: Failure[] = []; for (const result of results) { if (!result.ok) { ret.push(result); } } return ret; }; /** * Filter out failed results from a map with result values. * @param results - map of results to filter. */ export const successfulResultsFilterMap = ( results: ReadonlyMap>, ): ReadonlyMap> => { const ret: Map> = new Map(); for (const [k, result] of results) { if (result.ok) { ret.set(k, result); } } return ret; }; /** * Filter out successful results from a map with result values. * @param results - map of results to filter. */ export const failedResultsFilterMap = ( results: ReadonlyMap>, ): ReadonlyMap> => { const ret: Map> = new Map(); for (const [k, result] of results) { if (!result.ok) { ret.set(k, result); } } return ret; }; export type PartitionArrayPredicate = (val: T | U) => val is T; /** * Partition an array of values into two arrays based on evaluation of a binary predicate. * @param values - array of values to partition * @param predicate - binary predicate to evaluate partition group of each value */ export const partitionArray = ( values: readonly (T | U)[], predicate: PartitionArrayPredicate, ): readonly [readonly T[], readonly U[]] => { const ts: T[] = []; const us: U[] = []; for (const value of values) { if (predicate(value)) { ts.push(value); } else { us.push(value); } } return [ts, us]; }; /** * Partition array of values and errors into an array of values and an array of errors. * @param valuesAndErrors - array of values and errors */ export const partitionErrors = ( valuesAndErrors: readonly (T | Error)[], ): readonly [readonly T[], readonly Error[]] => { const [errors, values] = partitionArray(valuesAndErrors, isError); return [values, errors]; }; const isError = (value: T | Error): value is Error => { return value instanceof Error; }; export const pick = ( object: T, props: readonly U[], ): Pick => { const result = {} as Pick; for (const prop of props) { if (Object.prototype.hasOwnProperty.call(object, prop)) { result[prop] = object[prop]; } } return result; };