Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidystephenson/d1077792a585465f89b252a478eeb437 to your computer and use it in GitHub Desktop.
Save davidystephenson/d1077792a585465f89b252a478eeb437 to your computer and use it in GitHub Desktop.
// 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(`${this.name} is a ${this.isRare ? 'rare' : 'common'} ${this.type} with ${this.powerLevel} power`)
}
}
// Function to compare power levels of two items
function comparePower (item1: MagicalItem, item2: MagicalItem) {
if (item1.powerLevel > item2.powerLevel) {
return item1.name
}
return item2.name
}
// Generic class for inventory
class Inventory <T> {
private items: T[] = []
add (item: T) {
this.items.push(item)
}
getAll () {
return this.items
}
getProperty <K extends keyof T> (item: T, key: K) {
const value = item[key]
return value
}
}
// Example items
const bootsOfWisdom = new MagicalItem('Boots of Wisdom', 'armor', 9001, false)
const helmetOfSpeed = new MagicalItem('Helmet of Speed', 'armor', 9005, true)
// Create inventory and add items
const inventory = new Inventory<MagicalItem>()
// const result = inventory.getAll()
// const inventory2 = new Inventory<string>()
// const result2 = inventory2.getAll()
inventory.add(bootsOfWisdom)
inventory.add(helmetOfSpeed)
// Display all item info
const items = inventory.getAll()
for (const item of items) {
item.displayInfo()
}
// Compare power levels
const powerfulName = comparePower(bootsOfWisdom, helmetOfSpeed)
console.log(powerfulName)
// Access property using keyof
const value = inventory.getProperty(helmetOfSpeed, 'name')
console.log('value', value)
function capitalize(text: string){
console.log(text.toUpperCase())
}
capitalize(value)
const data = { name: 'Dorothy', occupation: 'writer', age: 25 }
function getValue <K extends keyof typeof data> (input: typeof data, key: K) {
return input[key]
}
const v = getValue(data, 'age')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment