lodash#partition TypeScript Examples

The following examples show how to use lodash#partition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: pureHelpers.ts    From webapp with MIT License 6 votes vote down vote up
filterAndWarn = <T>(
  arr: T[],
  conditioner: (item: T) => boolean,
  reason?: string
): T[] => {
  const [passed, dropped] = partition(arr, conditioner);
  if (dropped.length > 0) {
    console.warn(
      "Dropped",
      dropped,
      "items from array",
      reason ? `because ${reason}` : ""
    );
  }
  return passed;
}
Example #2
Source File: traceSummary.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
export function totalServiceTime(stamps: any, acc = 0): any {
  // This is a recursive function that performs arithmetic on duration
  // If duration is undefined, it will infinitely recurse. Filter out that case
  const filtered = stamps.filter((s: any) => s.duration);
  if (filtered.length === 0) {
    return acc;
  }
  const ts = minBy(filtered, (s: any) => s.timestamp);
  const [current, next] = partition(
    filtered,
    (t) => t.timestamp >= ts.timestamp && t.timestamp + t.duration <= ts.timestamp + ts.duration,
  );
  const endTs = Math.max(...current.map((t) => t.timestamp + t.duration));
  return totalServiceTime(next, acc + (endTs - ts.timestamp));
}
Example #3
Source File: search.ts    From nextclade with MIT License 6 votes vote down vote up
/** Parition array in 3 parts: items starting with term, items including term and items not including term */
export function search<T>(items: T[], term: string, getter: (item: T) => string[]) {
  const [itemsStartWith, itemsNotStartWith] = partition(items, (item) =>
    getter(item).some((candidate) => startsWithLowerCase(candidate, term)),
  )
  const [itemsInclude, itemsNotInclude] = partition(itemsNotStartWith, (item) =>
    getter(item).some((candidate) => includesLowerCase(candidate, term)),
  )
  return { itemsStartWith, itemsInclude, itemsNotInclude }
}
Example #4
Source File: sortResults.ts    From nextclade with MIT License 6 votes vote down vote up
export function sortByQcIssues(results: NextcladeResult[], direction: SortDirection) {
  // Only sort sequences that are ready (succeeded or failed). Put sequences still being analyzed sequences at the bottom.
  const [ready, rest] = partition(results, (result) => !isNil(result.result) || !isNil(result.error))

  const readySorted = orderBy(
    ready,
    (result) => {
      // Sort errored sequences as having very bad QC results
      const errorScore = isNil(result.error) ? 0 : 1e9
      const qcScore = result.result?.analysisResult.qc?.overallScore ?? defaultNumber(direction)
      return errorScore + qcScore
    },
    direction,
  )

  return [...readySorted, ...rest]
}
Example #5
Source File: sortResults.ts    From nextclade with MIT License 5 votes vote down vote up
export function sortByClade(results: NextcladeResult[], direction: SortDirection) {
  // Only sort sequences that are succeeded. Put errored sequences and sequences still being analyzed at the bottom.
  const [succeeded, rest] = partition(results, (result) => !!result.result)
  const succeededSorted = orderBy(succeeded, getClade, direction)
  return [...succeededSorted, ...rest]
}
Example #6
Source File: course.service.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
async getTACheckInCheckOutTimes(
    courseId: number,
    startDate: string,
    endDate: string,
  ): Promise<TACheckinTimesResponse> {
    const startDateAsDate = new Date(startDate);
    const endDateAsDate = new Date(endDate);
    if (startDateAsDate.getUTCDate() === endDateAsDate.getUTCDate()) {
      endDateAsDate.setUTCDate(endDateAsDate.getUTCDate() + 1);
    }

    const taEvents = await EventModel.find({
      where: {
        eventType: In([
          EventType.TA_CHECKED_IN,
          EventType.TA_CHECKED_OUT,
          EventType.TA_CHECKED_OUT_FORCED,
        ]),
        time: Between(startDateAsDate, endDateAsDate),
        courseId,
      },
      relations: ['user'],
    });

    const [checkinEvents, otherEvents] = partition(
      taEvents,
      (e) => e.eventType === EventType.TA_CHECKED_IN,
    );

    const taCheckinTimes: TACheckinPair[] = [];

    for (const checkinEvent of checkinEvents) {
      let closestEvent: EventModel = null;
      let mostRecentTime = new Date();
      const originalDate = mostRecentTime;

      for (const checkoutEvent of otherEvents) {
        if (
          checkoutEvent.userId === checkinEvent.userId &&
          checkoutEvent.time > checkinEvent.time &&
          checkoutEvent.time.getTime() - checkinEvent.time.getTime() <
            mostRecentTime.getTime() - checkinEvent.time.getTime()
        ) {
          closestEvent = checkoutEvent;
          mostRecentTime = checkoutEvent.time;
        }
      }

      const numHelped = await QuestionModel.count({
        where: {
          taHelpedId: checkinEvent.userId,
          helpedAt: Between(
            checkinEvent.time,
            closestEvent?.time || new Date(),
          ),
        },
      });

      taCheckinTimes.push({
        name: checkinEvent.user.name,
        checkinTime: checkinEvent.time,
        checkoutTime: closestEvent?.time,
        inProgress: mostRecentTime === originalDate,
        forced: closestEvent?.eventType === EventType.TA_CHECKED_OUT_FORCED,
        numHelped,
      });
    }

    return { taCheckinTimes };
  }
Example #7
Source File: MyMines.tsx    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
MyMines = () => {
  const { account } = useWeb3React()
  const { pools: poolsWithoutAutoVault, userDataLoaded } = usePools()
  const [stakedOnly, setStakedOnly] = useUserPoolStakedOnly()
  const {
    userData: { vvsAtLastUserAction, userShares },
    fees: { performanceFee },
    pricePerFullShare,
    totalVvsInVault,
  } = useVvsVault()
  const accountHasVaultShares = userShares && userShares.gt(0)
  
  const pools = useMemo(() => {
    const vvsPool = poolsWithoutAutoVault.find((pool) => pool.sousId === 0)
    const vvsAutoVault = { ...vvsPool, isAutoVault: true }
    return [vvsAutoVault, ...poolsWithoutAutoVault]
  }, [poolsWithoutAutoVault])

  // TODO aren't arrays in dep array checked just by reference, i.e. it will rerender every time reference changes?
  const [finishedPools, openPools] = useMemo(() => partition(pools, (pool) => pool.isFinished), [pools])

  const stakedOnlyOpenPools = useMemo(
    () =>
      openPools.filter((pool) => {
        if (pool.isAutoVault) {
          return accountHasVaultShares
        }
        return pool.userData && new BigNumber(pool.userData.stakedBalance).isGreaterThan(0)
      }),
    [openPools, accountHasVaultShares],
  )

  usePollFarmsPublicData()
  useFetchPublicPoolsData()
  useFetchUserPools(account)

  const chosenPools = stakedOnly ? stakedOnlyOpenPools : openPools

  return (
    <div>
      <CardLayout>
        {chosenPools.map((pool) =>
          pool.isAutoVault ? (
            <VvsVaultCard key="auto-vvs" pool={pool} showStakedOnly={stakedOnly} />
          ) : (
            // eslint-disable-next-line react/jsx-no-undef
            <PoolCard key={pool.sousId} pool={pool} account={account} />
          ),
        )}
      </CardLayout>
    </div>
  )
}