FPGA_WebLab/server/common.ts

74 lines
1.9 KiB
TypeScript

import _ from "lodash"
import { Option, Some, None } from "ts-results-es";
import { z } from "zod";
export const uint8 = z.number().nonnegative().lt(Math.pow(2, 8))
export const uint16 = z.number().nonnegative().lt(Math.pow(2, 16))
export const uint32 = z.number().nonnegative().lt(Math.pow(2, 32))
export const int8 = z.number().lt(Math.pow(2, 7)).gte(-Math.pow(2, 8))
export const int16 = z.number().lt(Math.pow(2, 15)).gte(-Math.pow(2, 16))
export const int32 = z.number().lt(Math.pow(2, 31)).gte(-Math.pow(2, 32))
export function UNUSED(_: unknown): void { }
export namespace fun {
export function numberToBytes(num: number, bytesLength: number): Uint8Array {
var array = new Uint8Array(bytesLength)
for (let i = 0; i < bytesLength; i++) {
array[i] = num & (0xFF << (i << 3))
}
return array
}
export function randomFromArray(array: Array<any>) {
return array[_.random(0, array.length - 1, false)]
}
export function isStringArray(obj: any): obj is Array<string> {
return z.string().array().safeParse(obj).success
}
export function isNumberArray(obj: any): obj is Array<number> {
return z.number().array().safeParse(obj).success
}
export function sqlConditionFromArray(
columnName: string,
array: Array<string>,
type: "AND" | "OR"
): Option<string> {
let condition: string = ""
const len = array.length
if (len == 0) {
return None
}
for (let i = 0; i < len; i++) {
condition.concat(`${columnName}=${array[i]}`)
if (i != len - 1) {
condition.concat(` ${type} `)
}
}
return new Some(condition)
}
export function sqlConditionFromString(
columnName: string,
str: string,
type: "AND" | "OR",
delimiter: string = " "
): Option<string> {
if (str.length == 0) {
return None
}
const array = str.split(delimiter)
return sqlConditionFromArray(columnName, array, type)
}
}