本文整理汇总了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) => {
示例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>;
示例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();
}
});
示例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,
示例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,
示例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);
}));
});