lodash#orderBy TypeScript Examples

The following examples show how to use lodash#orderBy. 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: utils.ts    From querybook with Apache License 2.0 7 votes vote down vote up
export function useRankedTags(tags: ITag[]) {
    // Note: orderBy is a stable sort, so the API order is kept
    return useMemo(
        () =>
            orderBy(
                tags,
                (tag) => {
                    if (tag.meta?.rank != null) {
                        return tag.meta.rank + BASELINE_TAG_RANK_SCORE;
                    } else if (!isEmpty(tag.meta)) {
                        return BASELINE_TAG_RANK_SCORE;
                    } else {
                        return 0;
                    }
                },
                ['desc']
            ),
        [tags]
    );
}
Example #2
Source File: conversation.repository.ts    From linkedin-private-api with MIT License 6 votes vote down vote up
private async fetchConversations({
    recipients,
    createdBefore,
  }: {
    recipients?: ProfileId | ProfileId[];
    createdBefore?: Date;
  }): Promise<Conversation[]> {
    const res = await this.client.request.conversation.getConversations({ recipients, createdBefore });
    const conversations = res.included.filter(p => p.$type === CONVERSATION_TYPE) as LinkedinConversation[];
    const profiles = getProfilesFromResponse<GetConversationsResponse>(res);

    return orderBy(transformConversations({ conversations, profiles }), 'lastActivityAt', 'desc');
  }
Example #3
Source File: RoundsTab.tsx    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
RoundsTab: React.FC<RoundsTabProps> = ({ hasBetHistory, bets }) => {
  const { t } = useTranslation()

  return hasBetHistory ? (
    <>
      {orderBy(bets, ['round.epoch'], ['desc']).map((bet) => (
        <HistoricalBet key={bet.id} bet={bet} />
      ))}
    </>
  ) : (
    <Box p="24px">
      <Heading size="lg" textAlign="center" mb="8px">
        {t('No prediction history available')}
      </Heading>
      <Text as="p" textAlign="center">
        {t(
          'If you are sure you should see history here, make sure you’re connected to the correct wallet and try again.',
        )}
      </Text>
    </Box>
  )
}
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: message-factories.ts    From linkedin-private-api with MIT License 6 votes vote down vote up
createGetMessagesResponse = (count: number) => {
  const resultMessages = createMessageEvent(count);
  const resultProfiles = createMiniProfile(count * 2); // two participants for each conversation
  const response = {
    data: {},
    included: [...resultMessages, ...resultProfiles],
  };

  return { response, resultMessages: orderBy(resultMessages, 'createdAt', 'desc'), resultProfiles };
}
Example #6
Source File: LocationContext.ts    From next-core with GNU General Public License v3.0 6 votes vote down vote up
matchStoryboard(storyboards: RuntimeStoryboard[]): RuntimeStoryboard {
    if (window.STANDALONE_MICRO_APPS && storyboards.length === 1) {
      return storyboards[0];
    }
    // Put apps with longer homepage before shorter ones.
    // E.g., `/legacy/tool` will match first before `/legacy`.
    // This enables two apps with relationship of parent-child of homepage.
    const sortedStoryboards = orderBy(
      storyboards,
      (storyboard) => storyboard.app?.homepage?.length ?? 0,
      "desc"
    );
    for (const storyboard of sortedStoryboards) {
      const homepage = storyboard.app?.homepage;
      if (typeof homepage === "string" && homepage[0] === "/") {
        if (
          matchPath(this.location.pathname, {
            path: homepage,
            exact: homepage === "/",
          })
        ) {
          return storyboard;
        }
      }
    }
  }
Example #7
Source File: utils.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
function sortForQueryEndingWithDot(
  transformedQuery: TransformedQueryString,
  itemsToFilter: NoteProps[]
) {
  const lowercaseQuery = transformedQuery.originalQuery.toLowerCase();

  // If the user enters the query 'data.' we want to keep items that have 'data.'
  // and sort the results in the along the following order:
  //
  // ```
  // data.driven                  (data. has clean-match, grandchild-free, 1st in hierarchy)
  // level1.level2.data.integer   (data. has clean-match, grandchild-free, 3rd in hierarchy)
  // l1.l2.l3.data.bool           (data. has clean-match, grandchild-free, 4th in hierarchy)
  // l1.with-data.and-child       (data. has partial match 2nd level)
  // l1.l2.with-data.and-child    (data. has partial match 3rd level)
  // level1.level2.data.integer.has-grandchild
  // l1.l2.with-data.and-child.has-grandchild
  // data.stub (Stub notes come at the end).
  // ```

  const itemsWithMetadata = itemsToFilter
    .map((item) => {
      // Firstly pre-process the items in attempt to find the match.
      const lowercaseFName = item.fname.toLowerCase();
      const matchIndex = lowercaseFName.indexOf(lowercaseQuery);
      return { matchIndex, item };
    })
    // Filter out items without a match.
    .filter((item) => item.matchIndex !== -1)
    // Filter out items where the match is at the end (match does not have children)
    .filter(
      (item) =>
        !(item.matchIndex + lowercaseQuery.length === item.item.fname.length)
    )
    .map((item) => {
      // Meaning the match takes up entire level of the hierarchy.
      // 'one.two-hi.three'->'two-hi.' is clean match while 'o-hi.' is a
      // match but not a clean one.
      const isCleanMatch =
        item.matchIndex === 0 ||
        item.item.fname.charAt(item.matchIndex - 1) === ".";

      const dotsBeforeMatch = countDots(
        item.item.fname.substring(0, item.matchIndex)
      );
      const dotsAfterMatch = countDots(
        item.item.fname.substring(item.matchIndex + lowercaseQuery.length)
      );
      const isStub = item.item.stub;
      const zeroGrandchildren = dotsAfterMatch === 0;
      return {
        isStub,
        dotsBeforeMatch,
        dotsAfterMatch,
        zeroGrandchildren,
        isCleanMatch,
        ...item,
      };
    });

  const sortOrder: { fieldName: string; order: "asc" | "desc" }[] = [
    { fieldName: "isStub", order: "desc" },
    { fieldName: "zeroGrandchildren", order: "desc" },
    { fieldName: "isCleanMatch", order: "desc" },
    { fieldName: "dotsAfterMatch", order: "asc" },
    { fieldName: "dotsBeforeMatch", order: "asc" },
  ];

  return orderBy(
    itemsWithMetadata,
    sortOrder.map((it) => it.fieldName),
    sortOrder.map((it) => it.order)
  ).map((item) => item.item);
}
Example #8
Source File: sort-by.pipe.ts    From blockcore-hub with MIT License 6 votes vote down vote up
transform(value: any[], order = '', column: string = ''): any[] {

        if (!value || order === '' || !order) {
            return value;

        }

        if (!column || column === '') {
            if (order === 'asc') {
                return value.sort();
            }
            else {
                return value.sort().reverse();
            }
        }

        if (value.length <= 1) {
            return value;
        }

        return orderBy(value, [column], [order]);
    }
Example #9
Source File: sortResults.ts    From nextclade with MIT License 6 votes vote down vote up
export function sortByFrameShifts(results: NextcladeResult[], direction: SortDirection) {
  return orderBy(
    results,
    (result) => {
      const frameShifts = result.result?.analysisResult.qc.frameShifts
      if (!frameShifts) {
        return defaultNumber(direction)
      }
      return frameShifts.totalFrameShifts * 1e3 + frameShifts.totalFrameShiftsIgnored
    },
    direction,
  )
}
Example #10
Source File: WalletTransactions.tsx    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
WalletTransactions: React.FC = () => {
  const { chainId } = useActiveWeb3React()
  const dispatch = useDispatch<AppDispatch>()
  const { t } = useTranslation()
  const allTransactions = useAllTransactions()
  const sortedTransactions = orderBy(allTransactions, 'addedTime', 'desc')

  const handleClearAll = () => {
    if (chainId) {
      dispatch(clearAllTransactions({ chainId }))
    }
  }

  return (
    <Box minHeight="120px">
      <Flex alignItems="center" justifyContent="space-between" mb="24px">
        <Text color="textSubtle" fontSize="12px" textTransform="uppercase" fontWeight="bold">
          {t('Recent Transactions')}
        </Text>
        {sortedTransactions.length > 0 && (
          <Button scale="sm" onClick={handleClearAll} variant="text" px="0">
            {t('Clear all')}
          </Button>
        )}
      </Flex>
      {sortedTransactions.length > 0 ? (
        sortedTransactions.map((txn) => <TransactionRow key={txn.hash} txn={txn} />)
      ) : (
        <Text textAlign="center">{t('No recent transactions')}</Text>
      )}
    </Box>
  )
}
Example #11
Source File: build.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @info this function must always return the entities in the same order to prevent unintended code changes
   * @returns all the entities for build order by date of creation
   */
  private async getOrderedEntities(
    buildId: string
  ): Promise<DataServiceGenerator.Entity[]> {
    const entities = await this.entityService.getEntitiesByVersions({
      where: {
        builds: {
          some: {
            id: buildId
          }
        }
      },
      include: ENTITIES_INCLUDE
    });
    return (orderBy(
      entities,
      entity => entity.createdAt
    ) as unknown) as DataServiceGenerator.Entity[];
  }
Example #12
Source File: formatSecurityReport.ts    From hub with Apache License 2.0 6 votes vote down vote up
formatSecurityReport = (
  vulnerabilities: Vulnerability[] | null
): { list: Vulnerability[]; summary: SecurityReportSummary } => {
  const list = vulnerabilities
    ? orderBy(
        vulnerabilities,
        [
          (vulnerability: Vulnerability) =>
            SEVERITY_ORDER.indexOf(vulnerability.Severity.toLowerCase() as VulnerabilitySeverity),
          (vulnerability: Vulnerability) => {
            const sources = vulnerability.CVSS ? Object.keys(vulnerability.CVSS) : [];
            const activeSource =
              vulnerability.SeveritySource && sources.includes(vulnerability.SeveritySource)
                ? vulnerability.SeveritySource
                : sources[0];
            if (sources.length > 0 && vulnerability.CVSS[activeSource]) {
              return vulnerability.CVSS[activeSource].V3Score || vulnerability.CVSS[activeSource].V2Score;
            }
          },
          'PkgName',
        ],
        ['asc', 'desc', 'asc']
      )
    : [];

  const sortedBySeverity = groupBy(vulnerabilities, 'Severity');

  const summary: SecurityReportSummary = {};
  for (let severity in VulnerabilitySeverity) {
    const value: VulnerabilitySeverity = severity.toLowerCase() as VulnerabilitySeverity;
    if (sortedBySeverity[severity.toUpperCase()]) {
      summary[value] = sortedBySeverity[severity.toUpperCase()].length;
    } else {
      summary[value] = 0;
    }
  }

  return { list: list, summary: summary };
}
Example #13
Source File: datasetStateSlice.ts    From prism-frontend with MIT License 6 votes vote down vote up
createTableData = (
  results: DataItem[],
  format: TableDataFormat,
): TableData => {
  const prefix = format === TableDataFormat.DATE ? 'd' : 't';
  const momentFormat =
    format === TableDataFormat.DATE ? DEFAULT_DATE_FORMAT : 'HH:mm';

  const sortedRows = orderBy(results, item => item.date).map((item, index) => ({
    ...item,
    day: `${prefix}${index + 1}`,
  }));

  const datesRows = sortedRows.reduce(
    (acc, obj) => ({
      ...acc,
      [obj.day]: moment(obj.date).format(momentFormat),
    }),
    {},
  );

  const valuesRows = sortedRows.reduce((acc, obj) => {
    if (!obj.value) {
      return acc;
    }

    return { ...acc, [obj.day]: obj.value.toString() };
  }, {});

  const columns = Object.keys(valuesRows);
  const data: TableData = {
    rows: [datesRows, valuesRows],
    columns,
  };

  return data;
}
Example #14
Source File: addon.utils.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
export function getAllProviders(addon: Addon): AddonExternalId[] {
  return orderBy(addon.externalIds, ["providerName"], ["asc"]);
}
Example #15
Source File: sortResults.ts    From nextclade with MIT License 5 votes vote down vote up
export function sortByMissing(results: NextcladeResult[], direction: SortDirection) {
  return orderBy(results, (result) => result.result?.analysisResult.totalMissing ?? defaultNumber(direction), direction)
}
Example #16
Source File: RoundsTab.tsx    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
RoundsTab: React.FC<RoundsTabProps> = ({ hasBetHistory, bets }) => {
  const { t } = useTranslation()
  const dispatch = useAppDispatch()
  const { account } = useWeb3React()
  const hasHistoryLoaded = useGetHasHistoryLoaded()
  const currentHistoryPage = useGetCurrentHistoryPage()
  const isFetchingHistory = useGetIsFetchingHistory()

  const handleClick = () => {
    dispatch(fetchNodeHistory({ account, page: currentHistoryPage + 1 }))
  }

  return hasBetHistory ? (
    <>
      <V1ClaimCheck />
      {orderBy(bets, ['round.epoch'], ['desc']).map((bet) => (
        <HistoricalBet key={bet.round.epoch} bet={bet} />
      ))}
      {hasBetHistory && !hasHistoryLoaded && (
        <Flex alignItems="center" justifyContent="center" py="24px">
          <Button variant="secondary" scale="sm" onClick={handleClick} disabled={isFetchingHistory}>
            {t('View More')}
          </Button>
        </Flex>
      )}
    </>
  ) : (
    <>
      <V1ClaimCheck />
      <Box p="24px">
        <Heading size="lg" textAlign="center" mb="8px">
          {t('No prediction history available')}
        </Heading>
        <Text as="p" textAlign="center">
          {t(
            'If you are sure you should see history here, make sure you’re connected to the correct wallet and try again.',
          )}
        </Text>
      </Box>
    </>
  )
}
Example #17
Source File: related-content.tsx    From nyxo-website with MIT License 5 votes vote down vote up
getArticles() {
    const { category, tags, articles, maxArticles } = this
    // (5.) We use an Identity Map to keep track of score
    interface Identity {
      [index: string]: {
        article: BlogPostNode
        points: number
      }
    }
    const identityMap: Identity = {}

    if (!!tags && tags.length === 0) {
      console.error("SimilarArticlesFactory: Tags not provided, use setTags().")
      return []
    }

    // if (!!category === false) {
    //   console.error(
    //     "SimilarArticlesFactory: Category not provided, use setCategory()."
    //   )
    //   return []
    // }

    function getSlug(article: BlogPostNode) {
      return article.frontmatter.slug as string
    }

    function addToMap(article: BlogPostNode) {
      const slug = getSlug(article)
      const exists = Object.prototype.hasOwnProperty.call(identityMap, slug)
      if (!exists) {
        identityMap[slug] = {
          article: article,
          points: 0,
        }
      }
    }

    // (7.) For category matches, we add 2 points
    function addCategoryPoints(article: BlogPostNode, category: string) {
      // const categoryPoints = 2
      // const slug = getSlug(article)
      // if (article.category === category) {
      //   identityMap[slug].points += categoryPoints
      // }
    }

    // (8.) For tags matches, we add 1 point
    function addTagsPoints(article: BlogPostNode, tags?: string[] | null[]) {
      const tagPoint = 1
      const slug = getSlug(article)

      article?.frontmatter?.tags?.forEach((aTag) => {
        if (includes(tags, aTag)) {
          identityMap[slug].points += tagPoint
        }
      })
    }

    function getIdentityMapAsArray() {
      return Object.keys(identityMap).map((slug) => identityMap[slug])
    }

    // (6.) Map over all articles, add to map and add points
    articles.forEach((article) => {
      addToMap(article)
      // addCategoryPoints(article, category) // We don't (yet) have categories
      addTagsPoints(article, tags)
    })

    // (9.) Convert the identity map to an array
    const arrayIdentityMap = getIdentityMapAsArray()

    // (10.) Use a lodash utility function to sort them
    // by points, from greatest to least
    const similarArticles = orderBy(arrayIdentityMap, ["points"], ["desc"])

    // (11. Take the max number articles requested)
    return similarArticles.splice(0, maxArticles)
  }
Example #18
Source File: RunUtils.ts    From kfp-tekton-backend with Apache License 2.0 5 votes vote down vote up
function extractMetricMetadata(runs: ApiRun[]): MetricMetadata[] {
  const metrics = Array.from(runsToMetricMetadataMap(runs).values());
  return orderBy(metrics, ['count', 'name'], ['desc', 'asc']);
}
Example #19
Source File: sortResults.ts    From nextclade with MIT License 5 votes vote down vote up
export function sortById(results: NextcladeResult[], direction: SortDirection) {
  return orderBy(results, (result) => result.index, direction)
}
Example #20
Source File: useGetTopPoolsByApr.tsx    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
useGetTopPoolsByApr = (isIntersecting: boolean) => {
  const dispatch = useAppDispatch()
  const { pools: poolsWithoutAutoVault } = usePools()
  const {
    fees: { performanceFee },
  } = useVvsVault()
  const performanceFeeAsDecimal = performanceFee && performanceFee / 100
  const [fetchStatus, setFetchStatus] = useState(FetchStatus.NOT_FETCHED)
  const [topPools, setTopPools] = useState<DeserializedPool[]>([null, null, null, null, null])

  const pools = useMemo(() => {
    const activePools = poolsWithoutAutoVault.filter((pool) => !pool.isFinished)
    const vvsPool = activePools.find((pool) => pool.sousId === 0)
    const vvsAutoVault = { ...vvsPool, isAutoVault: true }
    const vvsAutoVaultWithApr = { ...vvsAutoVault, apr: getAprData(vvsAutoVault, performanceFeeAsDecimal).apr }
    return [vvsAutoVaultWithApr, ...poolsWithoutAutoVault]
  }, [poolsWithoutAutoVault, performanceFeeAsDecimal])

  const vvsPriceUsdc = usePriceVvsUsdc()

  useEffect(() => {
    const fetchPoolsPublicData = async () => {
      setFetchStatus(FetchStatus.FETCHING)
      const blockNumber = await simpleRpcProvider.getBlockNumber()

      try {
        await dispatch(fetchVvsVaultFees())
        await dispatch(fetchPoolsPublicDataAsync(blockNumber))
        setFetchStatus(FetchStatus.SUCCESS)
      } catch (e) {
        console.error(e)
        setFetchStatus(FetchStatus.FAILED)
      }
    }

    if (isIntersecting && fetchStatus === FetchStatus.NOT_FETCHED) {
      fetchPoolsPublicData()
    }
  }, [dispatch, setFetchStatus, fetchStatus, topPools, isIntersecting])

  useEffect(() => {
    const getTopPoolsByApr = (activePools: DeserializedPool[]) => {
      const sortedByApr = orderBy(activePools, (pool: DeserializedPool) => pool.apr || 0, 'desc')
      setTopPools(sortedByApr.slice(0, 5))
    }
    if (fetchStatus === FetchStatus.SUCCESS && !topPools[0]) {
      getTopPoolsByApr(pools)
    }
  }, [setTopPools, pools, fetchStatus, vvsPriceUsdc, topPools, performanceFeeAsDecimal])

  return { topPools }
}
Example #21
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 #22
Source File: useGetTopFarmsByApr.tsx    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
useGetTopFarmsByApr = (isIntersecting: boolean) => {
  const dispatch = useAppDispatch()
  const { data: farms } = useFarms()
  const [fetchStatus, setFetchStatus] = useState(FetchStatus.NOT_FETCHED)
  const [topFarms, setTopFarms] = useState<FarmWithStakedValue[]>([null, null, null, null, null])
  const vvsPriceUsdc = usePriceVvsUsdc()

  useEffect(() => {
    const fetchFarmData = async () => {
      setFetchStatus(FetchStatus.FETCHING)
      const activeFarms = nonArchivedFarms.filter((farm) => farm.pid !== 0 && farm.multiplier !== '0X')
      try {
        await dispatch(fetchFarmsPublicDataAsync(activeFarms.map((farm) => farm.pid)))
        setFetchStatus(FetchStatus.SUCCESS)
      } catch (e) {
        console.error(e)
        setFetchStatus(FetchStatus.FAILED)
      }
    }

    if (isIntersecting && fetchStatus === FetchStatus.NOT_FETCHED) {
      fetchFarmData()
    }
  }, [dispatch, setFetchStatus, fetchStatus, topFarms, isIntersecting])

  useEffect(() => {
    const getTopFarmsByApr = (farmsState: DeserializedFarm[]) => {
      const farmsWithPrices = farmsState.filter((farm) => farm.lpTotalInQuoteToken && farm.quoteTokenPriceUsdc)
      const farmsWithApr: FarmWithStakedValue[] = farmsWithPrices.map((farm) => {
        const totalLiquidity = farm.lpTotalInQuoteToken.times(farm.quoteTokenPriceUsdc)
        const { vvsRewardsApr, lpRewardsApr } = getFarmApr(
          farm.poolWeight,
          vvsPriceUsdc,
          totalLiquidity,
          getAddress(farm.lpAddresses),
        )
        return { ...farm, apr: vvsRewardsApr, lpRewardsApr }
      })

      const sortedByApr = orderBy(farmsWithApr, (farm) => farm.apr + farm.lpRewardsApr, 'desc')
      setTopFarms(sortedByApr.slice(0, 5))
    }

    if (fetchStatus === FetchStatus.SUCCESS && !topFarms[0]) {
      getTopFarmsByApr(farms)
    }
  }, [setTopFarms, farms, fetchStatus, vvsPriceUsdc, topFarms])

  return { topFarms }
}
Example #23
Source File: sortResults.ts    From nextclade with MIT License 5 votes vote down vote up
export function sortByGaps(results: NextcladeResult[], direction: SortDirection) {
  return orderBy(
    results,
    (result) => result.result?.analysisResult.totalDeletions ?? defaultNumber(direction),
    direction,
  )
}
Example #24
Source File: hooks.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
useGetSortedRounds = () => {
  const roundData = useGetRounds()
  return orderBy(Object.values(roundData), ['epoch'], ['asc'])
}
Example #25
Source File: hooks.ts    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
useGetSortedRounds = () => {
  const roundData = useGetRounds()
  return orderBy(Object.values(roundData), ['epoch'], ['asc'])
}
Example #26
Source File: sortResults.ts    From nextclade with MIT License 5 votes vote down vote up
export function sortResultsByKey(results: NextcladeResult[], sorting: SortingKeyBased) {
  const { key, direction } = sorting
  return orderBy(results, (result) => result.result?.analysisResult.customNodeAttributes[key], direction)
}
Example #27
Source File: useGetTopFarmsByApr.tsx    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
useGetTopFarmsByApr = (isIntersecting: boolean) => {
  const dispatch = useAppDispatch()
  const { data: farms } = useFarms()
  const [fetchStatus, setFetchStatus] = useState(FetchStatus.NOT_FETCHED)
  const [topFarms, setTopFarms] = useState<FarmWithStakedValue[]>([null, null, null, null, null])
  const cakePriceUsdc = usePriceCakeUsdc()

  const { currentBlock } = useBlock()

  useEffect(() => {
    const fetchFarmData = async () => {
      setFetchStatus(FetchStatus.FETCHING)
      const activeFarms = nonArchivedFarms.filter((farm) => farm.pid !== 0 && farm.multiplier !== '0X')
      try {
        await dispatch(fetchFarmsPublicDataAsync(activeFarms.map((farm) => farm.pid)))
        setFetchStatus(FetchStatus.SUCCESS)
      } catch (e) {
        console.error(e)
        setFetchStatus(FetchStatus.FAILED)
      }
    }

    if (isIntersecting && fetchStatus === FetchStatus.NOT_FETCHED) {
      fetchFarmData()
    }
  }, [dispatch, setFetchStatus, fetchStatus, topFarms, isIntersecting])

  useEffect(() => {
    const getTopFarmsByApr = (farmsState: Farm[]) => {
      const farmsWithPrices = farmsState.filter((farm) => farm.lpTotalInQuoteToken && farm.quoteToken.usdcPrice)
      const farmsWithApr: FarmWithStakedValue[] = farmsWithPrices.map((farm) => {
        const totalLiquidity = new BigNumber(farm.lpTotalInQuoteToken).times(farm.quoteToken.usdcPrice)
        const { glideRewardsApr, lpRewardsApr } = getFarmApr(
          new BigNumber(farm.poolWeight),
          cakePriceUsdc,
          totalLiquidity,
          farm.lpAddresses[ChainId.MAINNET],
          currentBlock
        )
        return { ...farm, apr: glideRewardsApr, lpRewardsApr }
      })

      const sortedByApr = orderBy(farmsWithApr, (farm) => farm.apr + farm.lpRewardsApr, 'desc')
      setTopFarms(sortedByApr.slice(0, 5))
    }

    if (fetchStatus === FetchStatus.SUCCESS && !topFarms[0]) {
      getTopFarmsByApr(farms)
    }
  }, [setTopFarms, farms, fetchStatus, cakePriceUsdc, topFarms, currentBlock])

  return { topFarms }
}
Example #28
Source File: dates.ts    From aqualink-app with MIT License 5 votes vote down vote up
sortByDate = <T>(
  list: T[],
  dateKey: keyof T,
  order?: "asc" | "desc"
) =>
  orderBy(list, (item) => new Date(item[dateKey] as unknown as string), order)
Example #29
Source File: useGetTopPoolsByApr.tsx    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
useGetTopPoolsByApr = (isIntersecting: boolean) => {
  const dispatch = useAppDispatch()
  const { pools: poolsWithoutAutoVault } = useSelector((state: State) => ({
    pools: state.pools.data,
    userDataLoaded: state.pools.userDataLoaded,
  }))
  const {
    fees: { performanceFee },
  } = useCakeVault()
  const performanceFeeAsDecimal = performanceFee && performanceFee / 100
  const [fetchStatus, setFetchStatus] = useState(FetchStatus.NOT_FETCHED)
  const [topPools, setTopPools] = useState<Pool[]>([null, null, null, null, null])

  const pools = useMemo(() => {
    const activePools = poolsWithoutAutoVault.filter((pool) => !pool.isFinished)
    const cakePool = activePools.find((pool) => pool.sousId === 0)
    const cakeAutoVault = { ...cakePool, isAutoVault: true }
    const cakeAutoVaultWithApr = { ...cakeAutoVault, apr: getAprData(cakeAutoVault, performanceFeeAsDecimal).apr }
    return [cakeAutoVaultWithApr, ...poolsWithoutAutoVault]
  }, [poolsWithoutAutoVault, performanceFeeAsDecimal])

  const cakePriceUsdc = usePriceCakeUsdc()

  useEffect(() => {
    const fetchPoolsPublicData = async () => {
      setFetchStatus(FetchStatus.FETCHING)
      const blockNumber = await simpleRpcProvider.getBlockNumber()

      try {
        await dispatch(fetchCakeVaultFees())
        await dispatch(fetchPoolsPublicDataAsync(blockNumber))
        setFetchStatus(FetchStatus.SUCCESS)
      } catch (e) {
        console.error(e)
        setFetchStatus(FetchStatus.FAILED)
      }
    }

    if (isIntersecting && fetchStatus === FetchStatus.NOT_FETCHED) {
      fetchPoolsPublicData()
    }
  }, [dispatch, setFetchStatus, fetchStatus, topPools, isIntersecting])

  useEffect(() => {
    const getTopPoolsByApr = (activePools: Pool[]) => {
      const sortedByApr = orderBy(activePools, (pool: Pool) => pool.apr || 0, 'desc')
      setTopPools(sortedByApr.slice(0, 5))
    }
    if (fetchStatus === FetchStatus.SUCCESS && !topPools[0]) {
      getTopPoolsByApr(pools)
    }
  }, [setTopPools, pools, fetchStatus, cakePriceUsdc, topPools, performanceFeeAsDecimal])

  return { topPools }
}