Skip to content

Commit

Permalink
feat: typescriptify json
Browse files Browse the repository at this point in the history
  • Loading branch information
FauxFaux committed Apr 28, 2021
1 parent c8dbdc6 commit 1b1e65e
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,13 @@
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"rules": {
"@typescript-eslint/no-var-requires": "warn",
"@typescript-eslint/no-this-alias": "warn",
"@typescript-eslint/no-empty-function": "warn"
}
}
4 changes: 2 additions & 2 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json from './json';
export * as json from './json';
import alg from './alg';
import Graph from './graph';

export { Graph, json, alg };
export { Graph, alg };
23 changes: 10 additions & 13 deletions lib/json.js → lib/json.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
const _ = require('./lodash');
const Graph = require('./graph');
import * as _ from './lodash';
import Graph from './graph';

module.exports = {
write: write,
read: read,
};
export type Json = Record<string, any>;

function write(g) {
const json = {
export function write(g: Graph): Json {
const json: Json = {
options: {
directed: g.isDirected(),
multigraph: g.isMultigraph(),
Expand All @@ -22,11 +19,11 @@ function write(g) {
return json;
}

function writeNodes(g) {
function writeNodes(g: Graph) {
return _.map(g.nodes(), function (v) {
const nodeValue = g.node(v);
const parent = g.parent(v);
const node = { v: v };
const node: Json = { v: v };
if (!_.isUndefined(nodeValue)) {
node.value = nodeValue;
}
Expand All @@ -37,10 +34,10 @@ function writeNodes(g) {
});
}

function writeEdges(g) {
function writeEdges(g: Graph): Json {
return _.map(g.edges(), function (e) {
const edgeValue = g.edge(e);
const edge = { v: e.v, w: e.w };
const edge: Json = { v: e.v, w: e.w };
if (!_.isUndefined(e.name)) {
edge.name = e.name;
}
Expand All @@ -51,7 +48,7 @@ function writeEdges(g) {
});
}

function read(json) {
export function read(json: Record<string, any>): Graph {
const g = new Graph(json.options).setGraph(json.value);
_.each(json.nodes, function (entry) {
g.setNode(entry.v, entry.value);
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"@babel/preset-env": "^7.13.15",
"@babel/preset-typescript": "^7.13.0",
"@types/jest": "^26.0.23",
"@typescript-eslint/eslint-plugin": "^4.22.0",
"@typescript-eslint/parser": "^4.22.0",
"benchmark": "^2.1.4",
"eslint": "^7.25.0",
Expand Down

0 comments on commit 1b1e65e

Please sign in to comment.