Restructures demos.

This commit is contained in:
Henning Dieterichs
2020-03-18 11:18:48 +01:00
parent af52efdc51
commit 57146f79a0
45 changed files with 128 additions and 6 deletions

View File

@@ -0,0 +1,39 @@
import * as ts from "typescript";
export class MockLanguageServiceHost implements ts.LanguageServiceHost {
constructor(
private readonly files: Map<string, string>,
private readonly compilationSettings: ts.CompilerOptions
) {}
getScriptFileNames(): string[] {
return [...this.files.keys()];
}
getScriptVersion(fileName: string): string {
return ""; // our files don't change
}
getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined {
const content = this.files.get(fileName);
if (!content) {
return undefined;
}
return {
dispose() {},
getChangeRange: () => undefined,
getLength: () => content.length,
getText: (start, end) => content.substr(start, end - start),
};
}
getCompilationSettings(): ts.CompilerOptions {
return this.compilationSettings;
}
getCurrentDirectory(): string {
return "/";
}
getDefaultLibFileName(options: ts.CompilerOptions): string {
return ts.getDefaultLibFileName(options);
}
}

View File

@@ -0,0 +1,32 @@
import { getDataExtractorApi } from "@hediet/debug-visualizer-data-extraction";
// Registers all existing extractors.
getDataExtractorApi().registerDefaultExtractors();
getDataExtractorApi().registerExtractor({
id: "my-extractor",
getExtractions: (data, collector) => {
if (data instanceof Foo) {
collector.addExtraction({
id: "my-extractor",
name: "My Extractor",
priority: 2000,
extractData: () => ({ kind: { text: true }, text: "Foo" }),
});
}
},
});
setTimeout(() => {
new Main().run();
}, 0);
class Foo {}
class Main {
run() {
const f = new Foo();
// visualize `f` here!
debugger;
}
}

View File

@@ -0,0 +1,59 @@
import {
getDataExtractorApi,
createGraphFromPointers,
} from "@hediet/debug-visualizer-data-extraction";
getDataExtractorApi().registerDefaultExtractors();
setTimeout(() => {
new Main().run();
}, 0);
class Main {
run() {
const list = new DoublyLinkedList("1");
list.setNext(new DoublyLinkedList("2"));
list.next!.setNext(new DoublyLinkedList("3"));
list.next!.next!.setNext(new DoublyLinkedList("4"));
// Use `visualize()` as expression to visualize in the Debug Visualizer!
const visualize = () =>
createGraphFromPointers({ list, last, cur }, i => ({
id: i.id,
label: i.name,
color: finished.has(i) ? "lime" : undefined,
edges: [
{ to: i.next!, label: "next" },
{ to: i.prev!, label: "prev", color: "lightgray" },
].filter(r => !!r.to),
}));
const finished = new Set();
var cur: DoublyLinkedList | undefined = list;
// Reverses `list`. Finished nodes have correct pointers,
// their next node is also finished.
var last: DoublyLinkedList | undefined = undefined;
while (cur) {
cur.prev = cur.next;
cur.next = last;
finished.add(cur);
last = cur;
cur = cur.prev;
}
console.log("finished");
}
}
let id = 0;
class DoublyLinkedList {
public readonly id = (id++).toString();
constructor(public name: string) {}
next: DoublyLinkedList | undefined;
prev: DoublyLinkedList | undefined;
public setNext(val: DoublyLinkedList): void {
val.prev = this;
this.next = val;
}
}

View File

@@ -0,0 +1,12 @@
// visualize `data`
const data = new Array<number>();
let value = 0;
for (let i = 0; i < 100000; i++) {
const delta = Math.random() > 0.5 ? 1 : -1;
data.push(value);
value += delta;
if (i % 1000 === 0) {
debugger;
}
}

View File

@@ -0,0 +1,108 @@
// See https://codeburst.io/linked-lists-in-javascript-es6-code-part-1-6dd349c3dcc3
/*
After install the Debug Visualizer extension,
press F1, enter "Open Debug Visualizer" and
use the following code as expression to visualize.
Then, press F5 and chose "node".
```
hedietDbgVis.createGraphFromPointers(
hedietDbgVis.tryEval([
"list.head",
"newNode",
"node",
"previous",
this.constructor.name === "LinkedList" ? "this.head" : "err",
]),
n => ({
id: n.data,
color: "lightblue",
label: `${n.data}`,
edges: [{ to: n.next, label: "next" }].filter(i => !!i.to),
})
)
```
*/
class LinkedList {
constructor() {
this.head = null;
}
}
class Node {
constructor(data, next = null) {
(this.data = data), (this.next = next);
}
}
LinkedList.prototype.insertAtBeginning = function(data) {
// A newNode object is created with property data
// and next = null
let newNode = new Node(data);
// The pointer next is assigned head pointer
// so that both pointers now point at the same node.
newNode.next = this.head;
// As we are inserting at the beginning the head pointer
// needs to now point at the newNode.
this.head = newNode;
return this.head;
};
LinkedList.prototype.getAt = function(index) {
let counter = 0;
let node = this.head;
while (node) {
if (counter === index) {
return node;
}
counter++;
node = node.next;
}
return null;
};
// The insertAt() function contains the steps to insert
// a node at a given index.
LinkedList.prototype.insertAt = function(data, index) {
// if the list is empty i.e. head = null
if (!this.head) {
this.head = new Node(data);
return;
}
// if new node needs to be inserted at the front
// of the list i.e. before the head.
if (index === 0) {
this.head = new Node(data, this.head);
return;
}
// else, use getAt() to find the previous node.
const previous = this.getAt(index - 1);
let newNode = new Node(data);
newNode.next = previous.next;
previous.next = newNode;
return this.head;
};
const list = new LinkedList();
debugger; // Press F10 to continue
list.insertAtBeginning("4");
list.insertAtBeginning("3");
list.insertAtBeginning("2");
list.insertAtBeginning("1");
list.insertAt("3.5", 3);
console.log("finished");
// Some Plotting.
// Use `data` as expression to visualize.
const data = [];
for (let x = 0; x < 1000; x += 1) {
data.push(Math.sin(x / 10));
if (x % 10 === 0) {
console.log("step");
}
}

View File

@@ -0,0 +1,89 @@
import { getDataExtractorApi } from "@hediet/debug-visualizer-data-extraction";
getDataExtractorApi().registerDefaultExtractors();
/*
Visualize this expression:
```ts
hedietDbgVis.markedGrid(
array,
hedietDbgVis.tryEval(["i", "j", "left", "right"])
)
```
*/
// From https://github.com/AvraamMavridis/Algorithms-Data-Structures-in-Typescript/blob/master/algorithms/quickSort.md
const array = [1, 2, 33, 31, 1, 2, 63, 123, 6, 32, 943, 346, 24];
const sorted = quickSort(array, 0, array.length - 1);
console.log(sorted);
function swap(array: Array<number>, i: number, j: number) {
[array[i], array[j]] = [array[j], array[i]];
}
/**
* Split array and swap values
*
* @param {Array<number>} array
* @param {number} [left=0]
* @param {number} [right=array.length - 1]
* @returns {number}
*/
function partition(
array: Array<number>,
left: number = 0,
right: number = array.length - 1
) {
const pivot = Math.floor((right + left) / 2);
const pivotVal = array[pivot];
let i = left;
let j = right;
while (i <= j) {
while (array[i] < pivotVal) {
i++;
}
while (array[j] > pivotVal) {
j--;
}
if (i <= j) {
swap(array, i, j);
i++;
j--;
}
}
return i;
}
/**
* Quicksort implementation
*
* @param {Array<number>} array
* @param {number} [left=0]
* @param {number} [right=array.length - 1]
* @returns {Array<number>}
*/
function quickSort(
array: Array<number>,
left: number = 0,
right: number = array.length - 1
) {
let index;
if (array.length > 1) {
index = partition(array, left, right);
if (left < index - 1) {
quickSort(array, left, index - 1);
}
if (index < right) {
quickSort(array, index, right);
}
}
return array;
}

View File

@@ -0,0 +1,88 @@
import * as ts from "typescript";
import { getDataExtractorApi } from "@hediet/debug-visualizer-data-extraction";
import { MockLanguageServiceHost } from "./MockLanguageServiceHost";
// Registers all existing extractors.
getDataExtractorApi().registerDefaultExtractors();
setTimeout(() => {
new Main().run();
}, 0);
class Main {
run() {
const files = new Map<string, string>([
[
"main.ts",
`
class Test1 {
public foo(a: number) {
const x = { a: 5 };
}
}
`,
],
]);
const serviceHost = new MockLanguageServiceHost(files, {});
const baseService = ts.createLanguageService(
serviceHost,
ts.createDocumentRegistry()
);
const prog = baseService.getProgram()!;
debugger;
const c = prog.getTypeChecker();
let myValue = undefined; // Visualize `myValue` here!
const sourceFileAst = prog.getSourceFiles()[0];
myValue = sourceFileAst.getText();
console.log("myValue is the source code of the AST");
debugger;
myValue = {
sf: sourceFileAst,
fn: (n: ts.Node) => {
try {
const t = c.getTypeAtLocation(n);
return t ? c.typeToString(t) : undefined;
} catch (e) {
return "" + e;
}
},
};
console.log("myValue is AST, annotated with type information");
debugger;
myValue = {
sf: sourceFileAst,
fn: (n: ts.Node) => {
try {
const t = c.getSymbolAtLocation(n);
return t ? ts.SymbolFlags[t.flags] : undefined;
} catch (e) {
return "" + e;
}
},
};
console.log("myValue is AST, annotated with symbol information");
debugger;
for (const ident of identifiers) {
myValue = ident;
console.log("myValue is an identifier");
debugger;
}
}
}
/*
myValue = {
kind: { text: true, svg: true },
text: `
<svg height="210" width="500">
<polygon
points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;"
/>
</svg>
`,
};*/

View File

@@ -0,0 +1,37 @@
import {
enableHotReload,
registerUpdateReconciler,
getReloadCount,
hotCallExportedFunction,
} from "@hediet/node-reload";
enableHotReload();
registerUpdateReconciler(module);
import { registerDefaultExtractors } from "@hediet/debug-visualizer-data-extraction";
registerDefaultExtractors();
if (getReloadCount(module) === 0) {
// set interval so that the file watcher can detect changes in other files.
setInterval(() => {
hotCallExportedFunction(module, run);
}, 1000);
}
export function run() {
new Demo().run();
}
class Demo {
private f = new Foo(new Foo(undefined));
private arr = [new Foo(this.f), this.f];
private set = new Set([this.arr[0], new Foo(new Foo(this.arr[1]))]);
run() {
debugger;
}
}
class Foo {
constructor(public readonly next: Foo | undefined) {}
}