diff options
author | Ryan Dahl <ry@tinyclouds.org> | 2018-07-06 11:20:35 -0400 |
---|---|---|
committer | Ryan Dahl <ry@tinyclouds.org> | 2018-07-06 12:22:11 -0400 |
commit | fe404dfce901356dc7a5d38ba70029c72a946f27 (patch) | |
tree | b8ed0d3417e920da1fd4e6278046184d8205a237 /js/util.ts | |
parent | 21e1425656ccebb8d31da95acd83991fb7d728fd (diff) |
Import ts file from prototype without change
From commit 559453cf6cc88283bcf8fdeccd387458f5c63165
Excluding v8worker.d.ts, main.ts, and deno.d.ts.
Updates tslint.json to be original settings.
Diffstat (limited to 'js/util.ts')
-rw-r--r-- | js/util.ts | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/js/util.ts b/js/util.ts new file mode 100644 index 000000000..70cb79a55 --- /dev/null +++ b/js/util.ts @@ -0,0 +1,53 @@ +// Copyright 2018 Ryan Dahl <ry@tinyclouds.org> +// All rights reserved. MIT License. +import { debug } from "./main"; +import { TypedArray } from "./types"; + +// Internal logging for deno. Use the "debug" variable above to control +// output. +// tslint:disable-next-line:no-any +export function log(...args: any[]): void { + if (debug) { + console.log(...args); + } +} + +export function assert(cond: boolean, msg = "") { + if (!cond) { + throw Error(`Assert fail. ${msg}`); + } +} + +export function typedArrayToArrayBuffer(ta: TypedArray): ArrayBuffer { + const ab = ta.buffer.slice(ta.byteOffset, ta.byteOffset + ta.byteLength); + return ab as ArrayBuffer; +} + +export function arrayToStr(ui8: Uint8Array): string { + return String.fromCharCode(...ui8); +} + +// A `Resolvable` is a Promise with the `reject` and `resolve` functions +// placed as methods on the promise object itself. It allows you to do: +// +// const p = createResolvable<number>(); +// ... +// p.resolve(42); +// +// It'd be prettier to make Resolvable a class that inherits from Promise, +// rather than an interface. This is possible in ES2016, however typescript +// produces broken code when targeting ES5 code. +// See https://github.com/Microsoft/TypeScript/issues/15202 +// At the time of writing, the github issue is closed but the problem remains. +export interface Resolvable<T> extends Promise<T> { + resolve: (value?: T | PromiseLike<T>) => void; + // tslint:disable-next-line:no-any + reject: (reason?: any) => void; +} +export function createResolvable<T>(): Resolvable<T> { + let methods; + const promise = new Promise<T>((resolve, reject) => { + methods = { resolve, reject }; + }); + return Object.assign(promise, methods) as Resolvable<T>; +} |