Skip to content
Snippets Groups Projects
Commit d95206fe authored by marihachi's avatar marihachi
Browse files

#32

parent 4fe75b13
No related branches found
No related tags found
No related merge requests found
import { MfmNode, MfmText } from './node'; import { MfmNode } from './node';
export function createNode(type: string, props?: Record<string, any>, children?: MfmNode[]): MfmNode { export function createNode(type: string, props?: Record<string, any>, children?: MfmNode[]): MfmNode {
const node: any = { type }; const node: any = { type };
...@@ -11,54 +11,32 @@ export function createNode(type: string, props?: Record<string, any>, children?: ...@@ -11,54 +11,32 @@ export function createNode(type: string, props?: Record<string, any>, children?:
return node; return node;
} }
/** export function mergeText(nodes: (MfmNode | string)[]): MfmNode[] {
* @param predicate specifies whether to group the previous item and the current item const dest: MfmNode[] = [];
* @returns grouped items const storedChars: string[] = [];
*/
export function groupContinuous<T>(arr: T[], predicate: (prev: T, current: T) => boolean): T[][] {
const dest: any[][] = [];
for (let i = 0; i < arr.length; i++) { /**
if (i != 0 && predicate(arr[i - 1], arr[i])) { * Generate a text node from the stored chars, And push it.
dest[dest.length - 1].push(arr[i]); */
} function generateText() {
else { if (storedChars.length > 0) {
dest.push([arr[i]]); const textNode = createNode('text', { text: storedChars.join('') });
dest.push(textNode);
storedChars.length = 0;
} }
} }
return dest; for (const node of nodes) {
} if (typeof node == 'string') {
// Store the char.
export function mergeGroupedTrees<T>(groupedTrees: T[][]): T[] { storedChars.push(node);
return groupedTrees.reduce((acc, val) => acc.concat(val), ([] as T[]));
}
export function mergeText(trees: (MfmNode | string)[]): MfmNode[] {
// group trees
const groupes = groupContinuous(trees, (prev, current) => {
if (typeof prev == 'string' || typeof current == 'string') {
return (typeof prev == 'string' && typeof current == 'string');
} }
else { else {
return (prev.type == current.type); generateText();
dest.push(node);
} }
}); }
generateText();
// concatinate text
const concatGroupes = groupes.map((group) => {
if (typeof group[0] == 'string') {
return [
createNode('text', {
text: (group as string[]).join('')
})
];
}
return (group as MfmNode[]);
});
// merge groups
const dest = mergeGroupedTrees(concatGroupes);
return dest; return dest;
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment