godalming123 - Hi, I'm making a flashcards app ...

Hi, I'm making a flashcards app where you can create user defined flashcards, and each flashcard can depend on the contents of another flashcard.
const FlashcardDeck = z.map(z.string(), z.object({
dependencies: z.array(z.string()),
contents: FormattedText,
}))
const FlashcardDeck = z.map(z.string(), z.object({
dependencies: z.array(z.string()),
contents: FormattedText,
}))
Is it possible to force the dependencies to each be the key of an item in the FlashcardDeck map that is before the current item in the FlashcardDeck map in order to prevent circular dependencies?
Solution:
```ts const FlashcardDeck = z.map(z.string(), z.object({ dependencies: z.array(z.string()), contents: FormattedText, })).refine((deck) => {...
Jump to solution
2 Replies
godalming123
godalming123OP1h ago
I think that this code works:
Solution
godalming123
godalming1231h ago
const FlashcardDeck = z.map(z.string(), z.object({
dependencies: z.array(z.string()),
contents: FormattedText,
})).refine((deck) => {
const keys = Array.from(deck.keys())
let index = 0
for (const [_, flashcard] of deck.entries()) {
for (const dependency in flashcard.dependencies) {
const dependencyIndex = keys.indexOf(dependency)

// The dependency must be a flashcard
if (dependencyIndex == -1) {
return false
}

// The dependency must be defined before this flashcard (this is necersarry to prevent circular dependencies)
if (dependencyIndex >= index) {
return false
}
}
index += 1
}
})
const FlashcardDeck = z.map(z.string(), z.object({
dependencies: z.array(z.string()),
contents: FormattedText,
})).refine((deck) => {
const keys = Array.from(deck.keys())
let index = 0
for (const [_, flashcard] of deck.entries()) {
for (const dependency in flashcard.dependencies) {
const dependencyIndex = keys.indexOf(dependency)

// The dependency must be a flashcard
if (dependencyIndex == -1) {
return false
}

// The dependency must be defined before this flashcard (this is necersarry to prevent circular dependencies)
if (dependencyIndex >= index) {
return false
}
}
index += 1
}
})

Did you find this page helpful?