Created
May 3, 2025 16:56
-
-
Save davidystephenson/60081d958e1d128300a73930b9264915 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. Interface for Magical Item | |
interface IMagicalItem { | |
name: string | |
type: string | |
powerLevel: number | |
isRare: boolean | |
} | |
// 2. Class implementing IMagicalItem | |
class MagicalItem implements IMagicalItem { | |
name: string | |
type: string | |
powerLevel: number | |
isRare: boolean | |
constructor ( | |
name: string, | |
type: string, | |
powerLevel: number, | |
isRare: boolean | |
) { | |
this.name = name | |
this.type = type | |
this.powerLevel = powerLevel | |
this.isRare = isRare | |
} | |
displayInfo () { | |
console.log('name', this.name) | |
console.log('type', this.type) | |
console.log('powerLevel', this.powerLevel) | |
console.log('isRare', this.isRare) | |
} | |
} | |
// Function to compare power levels of two items | |
function comparePower (item1: IMagicalItem, item2: IMagicalItem) { | |
if (item1.powerLevel > item2.powerLevel) { | |
return item1.name | |
} | |
return item2.name | |
} | |
const a = new MagicalItem('a', 'type1', 9001, false) | |
const b = new MagicalItem('b', 'type1', 9002, true) | |
// Generic class for inventory | |
class Inventory <T> { | |
items: T[] = [] | |
add (item: T) { | |
this.items.push(item) | |
} | |
getAll() { | |
return this.items | |
} | |
// getProperty <K extends keyof T> (item: T, key: K) { | |
getProperty (item: T, key: keyof T) { | |
return item[key] | |
} | |
} | |
const stringInventory = new Inventory<string>() | |
stringInventory.add('hello') | |
stringInventory.add('goodybe') | |
const stringResult = stringInventory.getAll() | |
const stringProperty = stringInventory.getProperty('hi', 'length') | |
console.log('hi.length', stringProperty) | |
const numberInventory = new Inventory<number>() | |
numberInventory.add(1) | |
const numberResult = numberInventory.getAll() | |
// Example items | |
// Create inventory and add items | |
const magicInventory = new Inventory<IMagicalItem> | |
magicInventory.add(a) | |
magicInventory.add(b) | |
// Display all item info | |
const items = magicInventory.getAll() | |
console.log('items', items) | |
// Compare power levels | |
const powerful = comparePower(a, b) | |
console.log('powerful', powerful) | |
// Access property using keyof | |
const bRare = magicInventory.getProperty(b, 'isRare') | |
console.log('bRare', bRare) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment