lodash#memoize TypeScript Examples

The following examples show how to use lodash#memoize. 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 pali-wallet with MIT License 7 votes vote down vote up
getFetchWithTimeout = memoize((timeout) => {
  if (!Number.isInteger(timeout) || timeout < 1) {
    throw new Error('Must specify positive integer timeout.');
  }

  return async (url: string, opts: any) => {
    const abortController = new window.AbortController();

    const { signal } = abortController;

    const windowFetch = window.fetch(url, {
      ...opts,
      signal,
    });

    const timer = setTimeout(() => abortController.abort(), timeout);

    try {
      const response = await windowFetch;

      clearTimeout(timer);

      return response;
    } catch (error) {
      clearTimeout(timer);

      throw error;
    }
  };
})
Example #2
Source File: index.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 6 votes vote down vote up
protected getApiVaults = async (
        experimental = false,
        addresses?: string[]
    ): Promise<VaultApi[]> => {
        let vaults: VaultApi[];
        if (experimental) {
            vaults = await memoize(this.fetchExperimentalVaultData)();
        } else {
            vaults = await memoize(() => this.fetchVaultData(addresses))();
        }

        // The SDK may not return all strategies, so we need to query the subgraph
        const strategiesByVaults = await this.getStrategiesByVaults(
            vaults.map((vault) => vault.address)
        );
        const mergedVaults = vaults.map((vault) => ({
            ...vault,
            strategies: strategiesByVaults[vault.address.toLowerCase()],
        }));
        const sortedApiVaults = sortVaultsByVersion(mergedVaults);
        return sortedApiVaults;
    };
Example #3
Source File: path.ts    From free-swagger with MIT License 6 votes vote down vote up
createFilename = memoize(
  (tags: OpenAPIV2.TagObject[], tag: string) => {
    if (!tag) return ''
    if (hasChinese(tag)) {
      const item = tags!.find(({ name }) => name === tag)
      if (!item) return ''
      return item.description ? item.description : item.name
    } else {
      return tag
    }
  },
  (tags, tag) => tag
)
Example #4
Source File: env.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 6 votes vote down vote up
getEnv = memoize(
    (): Env => ({
        env: process.env.NODE_ENV,
        ethereumNetwork: 'homestead',
        infuraProjectId: process.env.INFURA_PROJECT_ID,
        alchemyKey:
            process.env.ALCHEMY_KEY || process.env.REACT_APP_ALCHEMY_KEY,
        fantomNode:
            process.env.FANTOM_NODE || process.env.REACT_APP_FANTOM_NODE,
        theGraphKey:
            process.env.THE_GRAPH_API_KEY ||
            process.env.REACT_APP_THE_GRAPH_API_KEY,
        fbApiKey: process.env.REACT_APP_FB_API_KEY,
        fbAuthDomain: process.env.REACT_APP_FB_AUTH_DOMAIN,
        fbProjectId: process.env.REACT_APP_FB_PROJECT_ID,
        // TODO: replace apiKey for production key, get from ENV variable
        ethplorerKey: 'freekey',
    })
)
Example #5
Source File: index.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 6 votes vote down vote up
public getVaults = async (
        allowList: string[] = [],
        queryParams: QueryParam = DEFAULT_QUERY_PARAM,
        experimental = false,
        addresses?: string[]
    ): Promise<Vault[]> => {
        const apiVaults = await memoize(() =>
            this.getApiVaults(experimental, addresses)
        )();
        const filterList = new Set(allowList.map((addr) => addr.toLowerCase()));

        let filteredVaults = filterVaultApiData(apiVaults, filterList);
        if (queryParams.pagination.offset >= filteredVaults.length) {
            return [];
        }
        filteredVaults = filteredVaults.slice(
            Math.max(0, queryParams.pagination.offset),
            Math.min(
                filteredVaults.length,
                queryParams.pagination.offset + queryParams.pagination.limit
            )
        );

        // TODO: this is mainly slow because we need to do a multicall to get
        // healthcheck statuses for all strategies, if this information is added
        // to the subgraph, we can optimize this to be much faster by only
        // performing multicalls if a user expands the vault card
        const vaults = await mapVaultApiDataToVault(
            filteredVaults,
            this.network
        );
        return vaults;
    };
Example #6
Source File: platform.ts    From ever-wallet-browser-extension with GNU General Public License v3.0 6 votes vote down vote up
getEnvironmentTypeCached = memoize((url): Environment => {
    const parseUrl = new URL(url)
    if (parseUrl.pathname === '/popup.html') {
        return ENVIRONMENT_TYPE_POPUP
    } else if (parseUrl.pathname === '/notification.html') {
        return ENVIRONMENT_TYPE_NOTIFICATION
    } else if (parseUrl.pathname === '/home.html') {
        return ENVIRONMENT_TYPE_FULLSCREEN
    }
    return ENVIRONMENT_TYPE_BACKGROUND
})
Example #7
Source File: text.ts    From S2 with MIT License 6 votes vote down vote up
measureTextWidth = memoize(
  (text: number | string = '', font: unknown): number => {
    if (!font) {
      return 0;
    }
    const { fontSize, fontFamily, fontWeight, fontStyle, fontVariant } =
      font as CSSStyleDeclaration;
    // copy G 里面的处理逻辑
    ctx.font = [fontStyle, fontVariant, fontWeight, `${fontSize}px`, fontFamily]
      .join(' ')
      .trim();

    return ctx.measureText(`${text}`).width;
  },
  (text: any, font) => [text, ...values(font)].join(''),
)
Example #8
Source File: create-config.ts    From prisma-nestjs-graphql with MIT License 5 votes vote down vote up
tsConfigFileExists = memoize((filePath: string) => {
  return existsSync(filePath);
})
Example #9
Source File: get-model-name.ts    From prisma-nestjs-graphql with MIT License 5 votes vote down vote up
export function createGetModelName(modelNames: string[]) {
  return memoize(tryGetName);

  function tryGetName(name: string): string | undefined {
    return getModelName({ modelNames, name });
  }
}
Example #10
Source File: index.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
public getNumVaults = async (experimental = false): Promise<number> => {
        const apiVaults = await memoize(() =>
            this.getApiVaults(experimental)
        )();
        return apiVaults.length;
    };
Example #11
Source File: base-data-set.ts    From S2 with MIT License 5 votes vote down vote up
/**
   * 查找字段信息
   */
  public getFieldMeta = memoize((field: string, meta?: Meta[]): Meta => {
    return find(this.meta || meta, (m: Meta) => m.field === field);
  });
Example #12
Source File: apisRequest.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
getApiData = memoize(_getApiData)
Example #13
Source File: apisRequest.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
querySubgraphData = memoize(querySubgraph, (...args) =>
    values(args).join('_')
)
Example #14
Source File: router.ts    From backstage with Apache License 2.0 5 votes vote down vote up
handleRequest = async (
  requests: IdentifiedPermissionMessage<EvaluatePermissionRequest>[],
  user: BackstageIdentityResponse | undefined,
  policy: PermissionPolicy,
  permissionIntegrationClient: PermissionIntegrationClient,
  authHeader?: string,
): Promise<IdentifiedPermissionMessage<EvaluatePermissionResponse>[]> => {
  const applyConditionsLoaderFor = memoize((pluginId: string) => {
    return new DataLoader<
      ApplyConditionsRequestEntry,
      ApplyConditionsResponseEntry
    >(batch =>
      permissionIntegrationClient.applyConditions(pluginId, batch, authHeader),
    );
  });

  return Promise.all(
    requests.map(({ id, resourceRef, ...request }) =>
      policy.handle(request, user).then(decision => {
        if (decision.result !== AuthorizeResult.CONDITIONAL) {
          return {
            id,
            ...decision,
          };
        }

        if (!isResourcePermission(request.permission)) {
          throw new Error(
            `Conditional decision returned from permission policy for non-resource permission ${request.permission.name}`,
          );
        }

        if (decision.resourceType !== request.permission.resourceType) {
          throw new Error(
            `Invalid resource conditions returned from permission policy for permission ${request.permission.name}`,
          );
        }

        if (!resourceRef) {
          return {
            id,
            ...decision,
          };
        }

        return applyConditionsLoaderFor(decision.pluginId).load({
          id,
          resourceRef,
          ...decision,
        });
      }),
    ),
  );
}
Example #15
Source File: reports.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
getReportsForStrategies = memoize(
    _getReportsForStrategies,
    (...args) => values(args).join('_')
)
Example #16
Source File: strategies.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
getStrategies = memoize(innerGetStrategies, (...args) =>
    values(args).join('_')
)
Example #17
Source File: strategies.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
getAllStrategies = memoize(_getAllStrategies)
Example #18
Source File: strategies.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
getGenLenderStrategy = memoize(_getGenLenderStrategy, (...args) =>
    values(args).join('_')
)
Example #19
Source File: vaults.ts    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
getVaultStrategyMetadata = memoize(
    _getVaultStrategyMetadata,
    (...args) => values(args).join('_')
)