Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidystephenson/b26a7f4e6b54d582ff93de18922795f5 to your computer and use it in GitHub Desktop.
Save davidystephenson/b26a7f4e6b54d582ff93de18922795f5 to your computer and use it in GitHub Desktop.
// Type definition for wand using tuple
type Wand = [core: string, length: number, material: string]
// Enum for house names
enum House {
Gryffindor = 'Gryffindor',
Slytherin = 'Slytherin'
}
// Type for character
interface Character {
name: string
age: number
isWizard: boolean
house: House
spells: string[]
wand: Wand
}
// Array to store all characters
const characters: Character[] = []
// Function to add a new character
function addCharacter (character: Character) {
characters.push(character)
}
// Function to display all characters
function displayCharacters () {
for (const character of characters) {
const label = character.isWizard ? 'wizard' : 'muggle'
const [core, length, material] = character.wand
const spells = character.spells.length > 0
? ` with the spells ${character.spells.join(' and ')}`
: ''
const wand = length > 0
? ` whose wand has a ${core} core, a length of ${length} cm, and a material of ${material}`
: ''
const message = `${character.name} is a ${character.age} year old ${label} of house ${character.house}${spells}${wand}.`
console.log(message)
}
}
// Function to filter characters by house
function filterByHouse (house: House) {
const filtered = characters.filter(character => character.house === house)
return filtered
}
// Function to count wizards vs muggles
function countByMagicalStatus () {
const wizards = characters.filter(character => character.isWizard)
const muggles = characters.filter(character => !character.isWizard)
const summary = { wizards: wizards.length, muggles: muggles.length }
return summary
}
// Sample data
addCharacter({
name: "Harry Potter",
age: 17,
isWizard: true,
house: House.Gryffindor,
spells: ["Expelliarmus", "Expecto Patronum"],
wand: ["Phoenix Feather", 11, "Holly"]
});
addCharacter({
name: "Hermione Granger",
age: 17,
isWizard: true,
house: House.Gryffindor,
spells: ["Alohomora", "Petrificus Totalus"],
wand: ["Dragon Heartstring", 10.75, "Vine"]
});
addCharacter({
name: "Dudley Dursley",
age: 18,
isWizard: false,
house: House.Slytherin,
spells: [],
wand: ["None", 0, "None"]
});
// Displaying characters
displayCharacters()
// Filter by house
console.log("\n Characters from Gryffindor:");
console.log(filterByHouse(House.Gryffindor));
// Magical status summary
const summary = countByMagicalStatus();
console.log(`\n Wizards: ${summary.wizards}, Muggles: ${summary.muggles}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment