From 8b2822221f5738368a12a9c01991ddc39d4f8e5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aykut=20Sara=C3=A7?= Date: Sun, 6 Feb 2022 13:20:35 +0300 Subject: [PATCH] convert parser into TS --- ...editor-parser.js => json-editor-parser.ts} | 21 ++++++++----------- tsconfig.json | 2 +- 2 files changed, 10 insertions(+), 13 deletions(-) rename src/utils/{json-editor-parser.js => json-editor-parser.ts} (71%) diff --git a/src/utils/json-editor-parser.js b/src/utils/json-editor-parser.ts similarity index 71% rename from src/utils/json-editor-parser.js rename to src/utils/json-editor-parser.ts index fce20ab..50ca0a2 100644 --- a/src/utils/json-editor-parser.js +++ b/src/utils/json-editor-parser.ts @@ -1,16 +1,12 @@ import { FlowElement } from "react-flow-renderer"; -/** - * @param {never[] | Object} input - * @returns {FlowElement[]} - */ -export const parser = (input) => { +export const parser = (input: string | string[]): FlowElement[] => { try { - input = JSON.parse(input); + if (typeof input !== "object") input = JSON.parse(input); if (!Array.isArray(input)) input = [input]; const extract = ( - os, + os: string[] | object[] | null, nextId = ( (id) => () => String(++id) @@ -43,8 +39,8 @@ export const parser = (input) => { })); }; - const relationships = (xs) => - xs.flatMap(({ id: target, children = [] }) => [ + const relationships = (xs: { id: string; children: never[] }[]) => { + return xs.flatMap(({ id: target, children = [] }) => [ ...children.map(({ id: source }) => ({ id: `e${source}-${target}`, source, @@ -52,15 +48,16 @@ export const parser = (input) => { })), ...relationships(children), ]); + }; - const flatten = (xs) => + const flatten = (xs: { id: string; children: never[] }[]) => xs.flatMap(({ children, ...rest }) => [rest, ...flatten(children)]); const res = extract(input); return [...flatten(res), ...relationships(res)]; } catch (error) { - console.error("An error occured while parsin JSON data!", error.stack); - return Array; + console.error("An error occured while parsin JSON data!"); + return []; } }; diff --git a/tsconfig.json b/tsconfig.json index 4ed67b0..a73a332 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,6 +17,6 @@ "incremental": true, "noImplicitAny": false }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "src/utils/json-editor-parser.js"], + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] }