I have an array of content blocks like so:
interface Content{
type: string,
content: string | string[]
}
const content: Content[] = [
{
type: "heading"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "list_item"
content: "whatever"
},
{
type: "list_item"
content: "whatever"
},
{
type: "list_item"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "heading"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "list_item"
content: "whatever"
},
{
type: "list_item"
content: "whatever"
},
{
type: "list_item"
content: "whatever"
},
{
type: "list_item"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
]
I’m trying to write a function which can merge these list_item
‘s into a list
with an array for the content of each. So, the output of the function for the above input should be:
[
{
type: "heading"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "list"
content: ["whatever","whatever","whatever"]
},
{
type: "para"
content: "whatever"
},
{
type: "heading"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "para"
content: "whatever"
},
{
type: "list"
content: ["whatever", "whatever", "whatever", "whatever"]
},
{
type: "para"
content: "whatever"
},
]
I’ve been trying to use a three-pointer system, looping over the array from i=1 to i < length – 1, tracking the prev
, curr
and next
blocks, however, I am getting very stuck with the logic and how I should handle the cases.
I feel like this is quite a simple problem for more experienced algorithm designers, so, I was looking for some guidance.