Move everything to core

This commit is contained in:
MindfulMinun committed 2022-07-26 01:41:08 -05:00
1 parent ad223ef14b
commit 7119ee6873
7 files changed
+2 -2

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
/// <reference lib="dom" />
import { templateNoop, HTML_ESCAPES, xss } from "./helpers.ts"
export { HTML_ESCAPES }
/**
* Parses HTML, kinda smart.
*
* As a function, it just parses the string as HTML. When used as a tagged template, expressions are XSS escaped using {@link xss}, except Nodes, which are added to the tree.
*
* ```js
* html("<p>Hello world!</p>")
* // DocumentFragment
* // └─ p
* // └─ "Hello world!"
* html`<strong>
* ${html`<em>Look ma, nested HTML!</em>`}
* ${`<img src="/bogus/path" onerror="alert('xss')">`}
* </strong>`
* // DocumentFragment
* // └─ strong
* // ├─ em
* // │ └─ "Look ma, nested HTML!"
* // └─ "<img src="/bogus/path" onerror="alert('xss')">"
* ```
* @author MindfulMinun
* @since 2020-06-23
*/
export function html(content: string): DocumentFragment
export function html(strings: TemplateStringsArray, ...exprs: unknown[]): DocumentFragment
export function html(strings: TemplateStringsArray | string, ...exprs: unknown[]): DocumentFragment {
const temp = document.createElement("template")
let out = ""
if (typeof strings === "string") {
temp.innerHTML = strings
return temp.content.cloneNode(true) as DocumentFragment
}
// Join the strings together
for (let i = 0; i < strings.length; i++) {
// If it's another Node, put a template in its place so we can replace it later
if (exprs[i] instanceof Node) {
out += strings[i] + `<template data-replaceindex="${i}"></template>`
continue
}
// Otherwise, just join the expressions together, escaping dynamic content
out += strings[i] + (typeof exprs[i] != 'undefined' ? xss("" + exprs[i]) : "")
}
temp.innerHTML = out
const clone = temp.content.cloneNode(true) as DocumentFragment
// Replace all templates with the real nodes
clone.querySelectorAll("template[data-replaceindex]").forEach(node => {
if (!(node instanceof HTMLElement)) return
if (!node.parentNode) return
const index = parseInt(node.getAttribute("data-replaceindex") || "", 10)
node.parentNode.replaceChild(exprs[index] as Node, node);
})
return clone
}
/**
* Creates a text node for use in the DOM. The text content is NOT escaped.
* @author MindfulMinun
* @since 2022-06-04
*/
export function textNode(templ: string): Text
export function textNode(templ: TemplateStringsArray, ...values: unknown[]): Text
export function textNode(templ: string | TemplateStringsArray, ...values: unknown[]): Text {
const string = templateNoop(templ, ...values)
return document.createTextNode(string)
}
/**
* Walks the DOM recursively, calling the callback for each node.
* @deprecated
* @param root - The root of the DOM walk
* @param callback - If this callback returns true, stop tree traversal.
* @param filters - A bitmask of what nodes to show. Defaults to `NodeFilter.SHOW_ELEMENT`.
* @author MindfulMinun
* @since 2020-06-29
*/
export function domWalker(
root: Node,
callback: (node: Node, root: Node, walker: TreeWalker) => boolean,
filters: number = NodeFilter.SHOW_ELEMENT
) {
const walker = document.createTreeWalker(root, filters);
let guard = false;
let current: Node | null = walker.currentNode
while (true) {
if (!current) break
if (guard) break
guard = callback.call(null, current, root, walker);
current = walker.nextNode()
}
}
+112
View File
@@ -0,0 +1,112 @@
/**
* HTML escape sequences for unsafe characters
*/
export const HTML_ESCAPES = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#x27;",
"/": "&#x2F;",
} as const
/**
* Removes indentation from multiline strings.
* @since 2021-08-07
*/
export function dedent(
templ: TemplateStringsArray | string,
...values: unknown[]
): string {
let strings = Array.from(typeof templ === 'string' ? [templ] : templ)
// 1. Remove trailing whitespace.
strings[strings.length - 1] = strings[strings.length - 1].trimRight()
// 2. Find all line breaks to determine the highest common indentation level.
const indentLengths = strings.reduce((arr, str) => {
const matches = str.match(/\n([\t ]+|(?!\s).)/g)
if (matches) {
return arr.concat(
matches.map((match) => match.match(/[\t ]/g)?.length ?? 0)
)
}
return arr
}, <number[]>[])
// 3. Remove the common indentation from all strings.
if (indentLengths.length) {
const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, 'g')
strings = strings.map((str) => str.replace(pattern, '\n'))
}
// 4. Remove leading whitespace.
strings[0] = strings[0].trimStart()
// 5. Perform interpolation.
let string = strings[0]
values.forEach((value, i) => {
// 5.1 Read current indentation level
const endentations = string.match(/(?:^|\n)( *)$/)
const endentation = endentations ? endentations[1] : ''
let indentedValue = value
// 5.2 Add indentation to values with multiline strings
if (typeof value === 'string' && value.includes('\n')) {
indentedValue = String(value)
.split('\n')
.map((str, i) => i === 0 ? str : `${endentation}${str}`)
.join('\n')
}
string += indentedValue + strings[i + 1]
})
return string
}
/**
* A no-operation function for tagged template string literals
* @author MindfulMinun
* @since 2022-05-20
*/
export function templateNoop(
templ: TemplateStringsArray | string,
...values: unknown[]
): string {
if (typeof templ === 'string') return templ
return templ.reduce((result, currentString, i) =>
result + currentString + (typeof values[i] !== 'undefined' ? values[i] : ''),
'' // Start with the empty string
)
}
/**
* Promise that resolves after timeout, optionally with a value to resolve with.
*
* @example
* // Play hide and seek, count to 100 (seconds)
* // Both methods are identical
* wait(100e3).then(() => "Ready or not, here I come!").then(seek)
* wait(100e3, "Ready or not, here I come!").then(seek)
* @since 2020-06-23
*/
export function wait(timeout: number): Promise<void>
export function wait<T>(timeout: number, resolveWith: T): Promise<T>
export function wait<T>(timeout: number, resolveWith?: T): Promise<T | void> {
return new Promise(resolve => setTimeout(() => resolve(resolveWith), timeout))
}
/**
* Escapes unsafe strings for use in HTML
*
* ```js
* xss(`<img src="/bogus/path" onerror="alert('xss')">`)
* ```
* @author MindfulMinun
* @since 2020-06-23
*/
export function xss(unsafe: string): string {
return unsafe.replace(/[&<>"'\/]/g, key => HTML_ESCAPES[key as keyof typeof HTML_ESCAPES])
}
+272
View File
@@ -0,0 +1,272 @@
/**
* Represents a tuple, or a homogenous array of a fixed length.
*
* const deck: Tuple<Card, 52> = [Card, Card, Card, ...];
*/
export type Tuple<
T,
N extends number,
R extends readonly T[] = [],
> = R['length'] extends N ? R : Tuple<T, N, readonly [T, ...R]>;
/**
* Chooses a random element from an array
*
* choose(document.all).click()
* @since 2020-06-29
*/
export function choose<T>(arr: T[]): T {
if (!arr.length) throw new Error('Cannot choose from an empty array')
return arr[Math.floor(Math.random() * arr.length)]
}
/**
* Creates an iterable that always yields the given value.
* @author MindfulMinun
* @since 2022-04-21
*/
export function* fill<T>(value = 0 as unknown as T, length = Infinity): Generator<T, void, unknown> {
for (let i = 0; i < length; i++)
yield value
}
/**
* Creates an iterable that yields numbers between a range.
* @author MindfulMinun
* @since 2022-04-27
*/
export function range(end: number): Generator<number, void, unknown>
export function range(start: number, end: number): Generator<number, void, unknown>
export function range(start: number, end: number, step: number): Generator<number, void, unknown>
export function* range(a: number, b?: number, c?: number) {
const [start, end, step] = (
typeof b === "undefined" ? [0, a, 1] :
typeof c === "undefined" ? [a, b, 1] : [a, b, Math.abs(c)]
)
const delta = end < start ? -step : step
for (let i = start; i < end; i += delta)
yield i
}
/**
* Given an iterable, yields the first `count` items, then returns.
* @author MindfulMinun
* @since 2022-07-07
*/
export function* limit<T>(count: number, iterable: Iterable<T>) {
let i = 0
for (const value of iterable) {
if (i < count) {
yield value
i++
} else break
}
return iterable
}
/**
* Given an async iterable, yields the first `count` items, then returns.
* @author MindfulMinun
* @since 2022-07-07
*/
export async function* limitAsync<T>(count: number, iterable: AsyncIterable<T>) {
let i = 0
for await (const value of iterable) {
if (i < count) {
yield value
i++
} else break
}
return iterable
}
/**
* Removes elements from an array. Non-destructive, as all array operations should be :D
*
* // Removes 'b', at index 1
* removeFromArraybyIndexes(['a', 'b', 'c'], 1) // ['a', 'c']
* // Removes 'b' and 'd', at indexes 1 and 3
* removeFromArraybyIndexes(['a', 'b', 'c', 'd'], [1, 3]) // ['a', 'c']
* @since 2020-07-12
*/
export function removeFromArraybyIndexes<T>(
arr: T[],
indexes: number | number[]
): T[] {
if (Array.isArray(indexes)) {
return arr.filter((_, i) => indexes.indexOf(i) === -1)
} else {
return arr.filter((_, i) => i !== indexes)
}
}
/**
* Divides an array into two by a given predicate function. Those that pass are put into the first, the rest are put in the second.
*
* @author MindfulMinun
* @since 2022-06-28
*/
export function divide<T>(list: T[], predicate: (this: typeof list, value: T, index: number, array: typeof list) => boolean): [T[], T[]] {
const pass: T[] = []
const fail: T[] = []
list.forEach((v, i, arr) => {
const passed = predicate.apply(list, [v, i, arr])
;(passed ? pass : fail).push(v)
})
return [pass, fail]
}
/**
* Shuffles an array. Note that this function swaps the elements
* *in place*, meaning the original array is modified.
* @since 2020-07-19
*/
export function shuffle<T>(arr: T[]): T[] {
let j, i
for (i = arr.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1))
swap(arr, i, j)
}
return arr
}
/**
* Swaps two elements of an array. Note that this function swaps
* the elements *in place*, meaning the original array is modified.
* @since 2020-07-19
*/
export function swap<T>(arr: T[], i: number, j: number): void {
const carry = arr[i]
arr[i] = arr[j]
arr[j] = carry
}
/**
* Helper class to handle events and turn them into async iterables
*
* ```ts
* const stream = new EventStream<MouseEvent>()
*
* document.body.addEventListener('click', ev => stream.emit(ev))
* wait(10e3).then(() => stream.end())
*
* for await (const event of stream) {
* alert("Clicked!")
* }
* ```
* @since 2021-08-07
*/
export class EventStream<T> {
#done: boolean
#events: T[]
#resolve: () => void
#promise!: Promise<void>
constructor() {
this.#done = false
this.#events = []
this.#resolve = () => { }
this.#defer()
}
#defer() {
this.#promise = new Promise(r => this.#resolve = r)
}
async*[Symbol.asyncIterator]() {
while (!this.#done) {
await this.#promise
yield* this.#events
this.#events = []
}
}
/**
* Dispatches an event. For-await-of listeners of this class instance will recieve this event.
* Note that once an event is emitted, it cannot be cancelled.
* @since 2021-08-07
*/
emit(event: T) {
this.#events.push(event)
this.#resolve()
this.#defer()
}
/**
* Waits for a specific event to be emitted according to a predicate.
*
* @example
* const stream = new EventStream<MouseEvent>()
* // Some events happen...
* const click = stream.once(ev => ev.type === 'click')
* @since 2021-12-22
*/
once(predicate: (value: T) => boolean) {
return once(this, predicate)
}
/**
* Stops the iterator. This terminates for-await-of loops listening for events,
* and any newly dispatched events will not be sent to the iterator.
* @since 2021-08-07
*/
end() {
this.#done = true
this.#resolve()
}
}
/**
* Wait for any async iterable to yield a specific value according to a predicate.
*
* @example
* const stream = new EventStream<MouseEvent>()
* // Some events happen...
* const click = once(stream, ev => ev.type === 'click')
* @since 2021-12-22
*/
export async function once<T>(source: AsyncIterable<T>, predicate: (value: T) => boolean) {
for await (const value of source) {
if (predicate(value)) return value
}
}
/**
* A "destructured" Promise, useful for waiting for callbacks.
* @example
* // When awaited, this function returns a promise that resolves to
* // an *OPEN* WebSocket
* () => {
* const sock = new WebSocket('wss://wss.example.com')
* const [p, res, rej] = pinkyPromise<typeof sock>()
* sock.onerror = err => rej(err)
* sock.onopen = () => res(sock)
* return p
* }
*
* @author MindfulMinun
* @since 2022-06-05
*/
export function pinkyPromise(): [Promise<void>, () => void, (reason?: unknown) => void]
export function pinkyPromise<T>(): [Promise<T>, (value: T) => void, (reason?: unknown) => void]
export function pinkyPromise<T>(): [
Promise<T | void>,
(value?: T | PromiseLike<T>) => void,
(reason?: unknown) => void
] {
let resolve: (value?: T | PromiseLike<T>) => void
let reject: (error: unknown) => void
// This works because callbacks to the Promise constructor are called synchronously.
const p = new Promise<T | void>((yay, nay) => {
resolve = value => yay(value)
reject = reason => nay(reason)
})
// HACK: This works because callbacks to the Promise constructor are called synchronously.
// In other words, they're immediately invoked, so they're available immediately after
// the assignment to `p`
return [p, resolve!, reject!]
}
+12
View File
@@ -0,0 +1,12 @@
/**
* Code I keep on rewriting for some reason
* @author MindfulMinun <https://benjic.xyz>
* @license MIT
*/
console.error("Hey there, past me! Please don't import `mod.ts`, instead import specific files!")
// export * from "./array.ts"
// export * from "./helpers.ts"
// export * from "./math.ts"
// export * from "./dom.ts"
+149
View File
@@ -0,0 +1,149 @@
import { swap } from './iterable.ts'
/**
* The base class for creating a (potentially seeded) random number generator.
* Provides a plethora of methods for manipulating objects with randomness.
* (I predicted you might need them, you are not random)
*
* Take a look at [this list of JavaScript PRNGs](https://github.com/bryc/code/blob/master/jshash/PRNGs.md)
* for guidance on implementation.
* @author MindfulMinun
* @since 2022-07-08
*/
export abstract class BaseRNG implements Iterable<number> {
/**
* This is the main number generation function. It should return a number
* between 0 (inclusive) and 1 (exclusive) as well as update its internal state.
* @author MindfulMinun
* @since 2022-07-16
*/
abstract nextValue(): number
/**
* Yields numbers between zero and one
* @author MindfulMinun
* @since 2022-07-16
*/
*[Symbol.iterator]() {
while (true) yield this.float()
}
/**
* Returns a floating point number between 0 (inclusive) and 1 (exclusive),
* using the algorithm implemented in {@link nextValue()}
* @author MindfulMinun
* @since 2022-07-16
*/
float() {
return this.nextValue()
}
/**
* Returns an integer between the provided bounds. This returns integers *up to* `upper`, without including it.
* @author MindfulMinun
* @since 2022-07-16
*/
int(upper: number): number
int(lower: number, upper: number): number
int(a: number, b?: number): number {
const [min, max] = typeof b === "undefined" ? [0, a] : [a, b]
return Math.floor(this.float() * (max - min + 1) + min)
}
/**
* Chooses a random element from a provided array
* @author MindfulMinun
* @since 2022-07-16
*/
choose<T>(arr: T[]) {
return arr[Math.floor(this.float() * arr.length)]
}
/**
* Shuffles an array. Note that this function swaps the elements
* *in place*, meaning the original array is modified.
* @author MindfulMinun
* @since 2022-07-16
*/
shuffle<T>(arr: T[]) {
let i, j
for (i = arr.length - 1; i > 0; i--) {
j = Math.floor(this.float() * (i + 1))
swap(arr, i, j)
}
return arr
}
/**
* Chooses an element from an array randomly, but with weighted probabilities.
* @param weights - An array of numbers. `weights[i]` corresponds to the probability
* of `items[i]` being chosen. The weights can be any nonnegative number, decimal or otherwise,
* and the sum of weights *does not* have to be 1.
* @example
* // 'paper' will be returned about half of the time, and 'rock' and 'scissors'
* // will be returned about a 1/4th of the time each.
* chooseWithWeights(
* ['rock', 'paper', 'scissors'],
* [1, 2, 1]
* )
* @author MindfulMinun
* @since 2022-07-16
*/
chooseWithWeights<T>(items: T[], weights: number[]) {
if (items.length != weights.length) throw Error(`Expected items and weights to have the same number of elements, but items has ${items.length} elements, and weights has ${weights.length}.`)
const sumOfWeights = weights.reduce((acc, v) => acc + v)
const picked = this.float() * sumOfWeights
let i = 0
let currentSum = 0
for (; i < weights.length - 1; i++) {
currentSum += weights[i]
if (currentSum > picked) break
}
return items[i]
}
}
/**
* A simple RNG which returns numbers generated by {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/random Math.random()}
* @author MindfulMinun
* @since 2022-07-08
*/
export class Random extends BaseRNG {
nextValue() { return Math.random() }
}
/**
* A seeded RNG which implements Mulberry32
* @author MindfulMinun
* @since 2022-07-08
*/
export class Mulberry32 extends BaseRNG {
#seed!: number
originalSeed!: number
constructor(seed = Date.now()) {
super()
this.resetSeed(seed)
}
/** Resets the seed */
resetSeed(seed = this.#seed) {
this.originalSeed = seed
this.#seed = seed
}
nextValue() {
// Mulberry32
let a = this.#seed
a |= 0
a = a + 0x6D2B79F5 | 0
let t = Math.imul(a ^ a >>> 15, 1 | a)
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t
this.#seed = a
return ((t ^ t >>> 14) >>> 0) / 4294967296
}
}
+15
View File
@@ -0,0 +1,15 @@
/**
* Run a shell command that can be aborted using an `AbortSignal`
* @since 2021-08-13
*/
export async function abortableExec(opts: { cmd: string[], signal?: AbortSignal }): Promise<void> {
const { cmd, signal } = opts
if (signal && signal.aborted) return
const p = Deno.run({
cmd,
stdout: "null"
})
signal && signal.addEventListener('abort', () => p.kill("SIGINT"))
await p.status()
return
}