Skip to content

Commit

Permalink
refactor(parseFormattedStringToDomElements.ts): improve type safety a…
Browse files Browse the repository at this point in the history
…nd readability of the interleave function

The changes made to the interleave function include adding type annotations to the parameters, improving type safety by specifying the types of the arrays passed to the function. Additionally, the code has been refactored to enhance readability by using arrow functions with clearer logic for each case in the match statement.
  • Loading branch information
ktun95 committed Nov 15, 2024
1 parent e047afe commit de993ab
Showing 1 changed file with 36 additions and 21 deletions.
57 changes: 36 additions & 21 deletions packages/ui-common/src/parseFormattedStringToDomElements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,48 @@ const parseIrregularTags = (s: string) =>

// Function to interleave two arrays
// Assumes that both trailing and leading arrays do not contain any nullish values
const interleave = (leading: readonly any[], trailing: readonly any[]) => {
const interleave = <A, B>(
leading: readonly A[],
trailing: readonly B[],
): Array<A | B | undefined> => {
const totalLength = leading.length + trailing.length
let cursorL = 0
let cursorT = 0

return AmakeBy(totalLength, (index) =>
match(index)
.when((i) => isEven(i) && leading[cursorL], () => {
const next = leading[cursorL]
cursorL += 1
return next
})
.when((i) => isEven(i) && trailing[cursorT], () => {
const next = trailing[cursorT]
cursorT += 1
return next
})
.when((i) => isOdd(i) && trailing[cursorT], () => {
const next = trailing[cursorT]
cursorT += 1
return next
})
.when((i) => isOdd(i) && leading[cursorL], () => {
const next = leading[cursorL]
cursorL += 1
return next
})
.when(
(currentIndex) => isEven(currentIndex) && leading[cursorL],
() => {
const next = leading[cursorL]
cursorL += 1
return next
},
)
.when(
(currentIndex) => isEven(currentIndex) && trailing[cursorT],
() => {
const next = trailing[cursorT]
cursorT += 1
return next
},
)
.when(
(currentIndex) => isOdd(currentIndex) && trailing[cursorT],
() => {
const next = trailing[cursorT]
cursorT += 1
return next
},
)
.when(
(currentIndex) => isOdd(currentIndex) && leading[cursorL],
() => {
const next = leading[cursorL]
cursorL += 1
return next
},
)
.otherwise(() => undefined),
)
}
Expand Down

0 comments on commit de993ab

Please sign in to comment.