• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript underscore.memoize函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中underscore.memoize函数的典型用法代码示例。如果您正苦于以下问题:TypeScript memoize函数的具体用法?TypeScript memoize怎么用?TypeScript memoize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了memoize函数的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: as

  InventoryBucket: { [hash: number]: DestinyInventoryBucketDefinition };
  Class: { [hash: number]: DestinyClassDefinition };
  Gender: { [hash: number]: DestinyGenderDefinition };
  Race: { [hash: number]: DestinyRaceDefinition };
  Faction: { [hash: number]: DestinyFactionDefinition };
  ItemTierType: { [hash: number]: DestinyItemTierTypeDefinition };
  ActivityMode: { [hash: number]: DestinyActivityModeDefinition };
}

/**
 * Manifest database definitions. This returns a promise for an
 * objet that has a property named after each of the tables listed
 * above (defs.TalentGrid, etc.).
 */
export const getDefinitions = _.memoize(getDefinitionsUncached) as () => IPromise<
  D2ManifestDefinitions
>;

/**
 * Manifest database definitions. This returns a promise for an
 * objet that has a property named after each of the tables listed
 * above (defs.TalentGrid, etc.).
 */
function getDefinitionsUncached(): IPromise<D2ManifestDefinitions> {
  // Wrap in IPromise until we're off Angular
  return $q.when(D2ManifestService.getManifest()).then((db) => {
    const defs = {};

    // Load objects that lazily load their properties from the sqlite DB.
    lazyTables.forEach((tableShort) => {
开发者ID:bhollis,项目名称:DIM,代码行数:30,代码来源:d2-definitions.service.ts


示例2: getDefinitions

export const getBuckets = _.memoize(() => {
  return getDefinitions().then((defs) => {
    const buckets: InventoryBuckets = {
      byHash: {}, // numeric hash -> bucket
      byId: {}, // BUCKET_LEGS -> bucket
      byType: {}, // DIM types ("ClassItem, Special") -> bucket
      byCategory: {}, // Mirrors the dimCategory heirarchy
      unknown: {
        id: 'BUCKET_UNKNOWN',
        description: 'Unknown items. DIM needs a manifest update.',
        name: 'Unknown',
        hash: -1,
        hasTransferDestination: false,
        category: BucketCategory.Item,
        capacity: Number.MAX_SAFE_INTEGER,
        sort: 'Unknown',
        type: 'Unknown',
        accountWide: false
      },
      setHasUnknown() {
        this.byCategory[this.unknown.sort] = [this.unknown];
        this.byId[this.unknown.id] = this.unknown;
        this.byType[this.unknown.type] = this.unknown;
      }
    };
    _.each(defs.InventoryBucket, (def: any) => {
      if (def.enabled) {
        const id = def.bucketIdentifier;
        const type = bucketToType[def.bucketIdentifier];
        let sort: string | undefined;
        if (type) {
          sort = typeToSort[type];
        } else if (vaultTypes[id]) {
          sort = vaultTypes[id];
        }

        const bucket: InventoryBucket = {
          id,
          description: def.bucketDescription,
          name: def.bucketName,
          hash: def.hash,
          hasTransferDestination: def.hasTransferDestination,
          capacity: def.itemCount,
          accountWide: false,
          category: BucketCategory.Item,
          type: bucketToType[def.bucketIdentifier],
          sort
        };

        if (bucket.type) {
          buckets.byType[bucket.type] = bucket;
        }

        if (sort) {
          // Add an easy helper property like "inPostmaster"
          bucket[`in${sort}`] = true;
        }

        buckets.byHash[bucket.hash] = bucket;
        buckets.byId[bucket.id] = bucket;
      }
    });

    _.each(buckets.byHash, (bucket: InventoryBucket) => {
      if (bucket.sort && sortToVault[bucket.sort]) {
        bucket.vaultBucket = buckets.byId[sortToVault[bucket.sort]];
      }
    });

    _.each(D1Categories, (types, category) => {
      buckets.byCategory[category] = _.compact(
        types.map((type) => {
          return buckets.byType[type];
        })
      );
    });

    return buckets;
  });
}) as () => IPromise<InventoryBuckets>;
开发者ID:bhollis,项目名称:DIM,代码行数:80,代码来源:d1-buckets.service.ts


示例3: importAsmJs

export const requireSqlLib = _.memoize(() => {
  function importAsmJs() {
    delete window.Module;
    delete window.SQL;
    console.log('Using asm.js SQLite');
    // tslint:disable-next-line:space-in-parens
    return import(/* webpackChunkName: "sqlLib" */ 'sql.js');
  }

  if ($featureFlags.wasm && typeof WebAssembly === 'object') {
    return new Promise((resolve, reject) => {
      let loaded = false;

      window.Module = {
        locateFile() {
          return sqlWasmBinaryPath;
        }
      };
      window.SQL = {
        onRuntimeInitialized() {
          if (!loaded) {
            loaded = true;

            try {
              // Do a self-test
              const db = new window.SQL.Database();
              db.run('CREATE TABLE hello (a int, b char);');
              db.run("INSERT INTO hello VALUES (0, 'hello');");
              db.exec('SELECT * FROM hello');
            } catch (e) {
              console.error('Failed to load WASM SQLite, falling back', e);
              importAsmJs().then(resolve, reject);
              return;
            }

            console.info('Using WASM SQLite');
            resolve(window.SQL);
            delete window.SQL;
          }
        }
      };

      // Give it 10 seconds to load
      setTimeout(() => {
        if (!loaded) {
          loaded = true;

          // Fall back to the old one
          importAsmJs().then(resolve, reject);
        }
      }, 10000);

      const head = document.getElementsByTagName('head')[0];
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = sqlWasmPath;
      script.async = true;
      head.appendChild(script);
    });
  } else {
    return importAsmJs();
  }
});
开发者ID:bhollis,项目名称:DIM,代码行数:63,代码来源:database.ts


示例4: setHasUnknown

  byHash: { [hash: number]: DimInventoryBucket };
  byType: { [type: string]: DimInventoryBucket };
  byId: { [hash: number]: DimInventoryBucket };
  byCategory: { [category: string]: DimInventoryBucket[] };
  unknown: DimInventoryBucket; // TODO: get rid of this?
  setHasUnknown();
}

const typeToSort: { [type: string]: string } = {};
_.each(D2Categories, (types, category) => {
  types.forEach((type) => {
    typeToSort[type] = category;
  });
});

export const getBuckets = _.memoize(getBucketsUncached) as () => IPromise<DimInventoryBuckets>;

function getBucketsUncached() {
  return getDefinitions().then((defs) => {
    const buckets: DimInventoryBuckets = {
      byHash: {}, // numeric hash -> bucket
      byType: {}, // names ("ClassItem, Special") -> bucket
      byId: {}, // TODO hack
      byCategory: {}, // Mirrors the dimCategory heirarchy
      unknown: {
        description: 'Unknown items. DIM needs a manifest update.',
        name: 'Unknown',
        id: -1,
        hash: -1,
        hasTransferDestination: false,
        capacity: Number.MAX_SAFE_INTEGER,
开发者ID:delphiactual,项目名称:DIM,代码行数:31,代码来源:d2-buckets.service.ts


示例5: chooseMoveAsideItem


//.........这里部分代码省略.........
      junk: 2,
      // Favorites you want on your character
      favorite: 3
    };

    // A sort for items to use for ranking which item to move
    // aside. When moving from the vault we'll choose the
    // "largest" item, while moving from a character to the
    // vault (or another character) we'll use the "smallest".
    // Note, in JS "true" is greater than "false".
    const itemValueComparator: (a: DimItem, b: DimItem) => number = chainComparator(
      // prefer same type over everything
      compareBy((i) => i.type === item.typeName),
      // Engrams prefer to be in the vault, so not-engram is larger than engram
      compareBy((i) => !i.isEngram()),
      // Never unequip something
      compareBy((i) => i.equipped),
      // Always prefer keeping something that was manually moved where it is
      compareBy((i) => store.isVault ? (-1 * i.lastManuallyMoved) : (i.lastManuallyMoved)),
      // Prefer things this character can use
      compareBy((i) => !store.isVault && i.canBeEquippedBy(store)),
      // Tagged items sort by the value of their tags
      compareBy((i) => (i.dimInfo && i.dimInfo.tag) ? tagValue[i.dimInfo.tag] : 0),
      // Prefer moving lower-tier
      compareBy((i) => tierValue[i.tier]),
      // Prefer keeping higher-stat items
      compareBy((i) => i.primStat && i.primStat.value)
    );

    // Sort all candidates
    moveAsideCandidates.sort(store.isVault ? reverseComparator(itemValueComparator) : itemValueComparator);

    // A cached version of the space-left function
    const cachedSpaceLeft = _.memoize((store, item) => {
      return moveContext.spaceLeft(store, item);
    }, (store, item) => {
      // cache key
      if (item.maxStackSize > 1) {
        return store.id + item.hash;
      } else {
        return store.id + item.type;
      }
    });

    let moveAsideCandidate: {
      item: DimItem;
      target: DimStore;
    } | undefined;

    const storeService = getStoreService(item);
    const vault = storeService.getVault()!;
    moveAsideCandidates.find((candidate) => {
      // Other, non-vault stores, with the item's current
      // owner ranked last, but otherwise sorted by the
      // available space for the candidate item.
      const otherNonVaultStores = _.sortBy(
        otherStores.filter((s) => !s.isVault && s.id !== item.owner),
        (s) => cachedSpaceLeft(s, candidate)).reverse();
      otherNonVaultStores.push(storeService.getStore(item.owner)!);
      const otherCharacterWithSpace = otherNonVaultStores.find((s) => cachedSpaceLeft(s, candidate));

      if (store.isVault) { // If we're moving from the vault
        // If there's somewhere with space, put it there
        if (otherCharacterWithSpace) {
          moveAsideCandidate = {
            item: candidate,
开发者ID:delphiactual,项目名称:DIM,代码行数:67,代码来源:dimItemService.factory.ts


示例6: get

export const getDefinitions = _.memoize(() => {
  return $q.when(D1ManifestService.getManifest()
    .then((db) => {
      const defs = {};

      // Load objects that lazily load their properties from the sqlite DB.
      lazyTables.forEach((tableShort) => {
        const table = `Destiny${tableShort}Definition`;
        defs[tableShort] = {
          get(name) {
            if (this.hasOwnProperty(name)) {
              return this[name];
            }
            const val = D1ManifestService.getRecord(db, table, name);
            this[name] = val;
            return val;
          }
        };
      });

      // Resources that need to be fully loaded (because they're iterated over)
      eagerTables.forEach((tableShort) => {
        const table = `Destiny${tableShort}Definition`;
        defs[tableShort] = D1ManifestService.getAllRecords(db, table);
      });

      return defs;
    })
    .catch((e) => {
      console.error(e);
      return $q.reject(e);
    }));
});
开发者ID:delphiactual,项目名称:DIM,代码行数:33,代码来源:d1-definitions.service.ts



注:本文中的underscore.memoize函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript underscore.method函数代码示例发布时间:2022-05-25
下一篇:
TypeScript underscore.max函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap