Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
milesstoetzner committed Sep 4, 2023
1 parent 5032503 commit 340810f
Show file tree
Hide file tree
Showing 9 changed files with 32 additions and 1,044 deletions.
6 changes: 0 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
"js-yaml": "^4.1.0",
"lodash": "^4.17.21",
"mqtt": "^5.0.4",
"node-cron": "^3.0.2",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2",
"socketcan": "^4.0.3",
Expand All @@ -64,11 +63,9 @@
"@types/cors": "^2.8.13",
"@types/express": "^4.17.17",
"@types/js-yaml": "^4.0.5",
"@types/kill-port": "^2.0.0",
"@types/lodash": "^4.14.194",
"@types/mocha": "^10.0.1",
"@types/node": "^18.15.11",
"@types/node-cron": "^3.0.7",
"@types/uuid": "^9.0.1",
"@types/ws": "^8.5.5",
"@typescript-eslint/eslint-plugin": "^5.58.0",
Expand All @@ -85,9 +82,6 @@
"mocha": "^10.2.0",
"nodemon": "^2.0.22",
"nyc": "^15.1.0",
"open-cli": "^7.2.0",
"pkg": "^5.8.1",
"postinstall-postinstall": "^2.1.0",
"prettier": "^2.8.7",
"prettier-plugin-organize-imports": "^3.2.2",
"source-map-support": "^0.5.21",
Expand Down
3 changes: 1 addition & 2 deletions src/core/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ export class Bridge {
std.log('bridging', {message})

assert.isNumber(message.id)
assert.isArray(message.data)
message.data.forEach(assert.isNumber)
assert.isNumbers(message.data)

await this.target.send(message)
if (!this.source.continuous) await this.stop()
Expand Down
2 changes: 1 addition & 1 deletion src/source/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export abstract class Source {
protected readyPromise

protected constructor() {
this.readyPromise = utils.createOutsidePromise()
this.readyPromise = utils.createDecomposedPromise()
}

async start() {
Expand Down
2 changes: 1 addition & 1 deletion src/target/target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as utils from '#utils'
export abstract class Target {
protected readyPromise
protected constructor() {
this.readyPromise = utils.createOutsidePromise()
this.readyPromise = utils.createDecomposedPromise()
}

async start() {
Expand Down
12 changes: 0 additions & 12 deletions src/utils/crypto.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/utils/files.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as check from '#check'
import * as crypto from '#crypto'
import * as fs from 'fs'
import * as yaml from 'js-yaml'
import _ from 'lodash'
import os from 'os'
import * as path from 'path'
import {v4 as uuid4} from 'uuid'
import * as utils from './utils'

export const TMP_PREFIX = 'stoetzms-can2x-'
Expand Down Expand Up @@ -167,7 +167,7 @@ export function getName(file: string) {
}

export function temporary(name?: string) {
return path.join(os.tmpdir(), TMP_PREFIX + (name || crypto.generateNonce()))
return path.join(os.tmpdir(), TMP_PREFIX + (name || uuid4()))
}

export function stat(file: string) {
Expand Down
150 changes: 1 addition & 149 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,69 +1,4 @@
import * as assert from '#assert'
import * as check from '#check'
import process from 'process'

export function mapIsEmpty<K, V>(map: Map<K, V>) {
return map.size === 0
}

export function mapSome<K, V>(map: Map<K, V>, fn: (value: V) => boolean) {
for (const [key, value] of map) {
if (fn(value)) return true
}
return false
}

export function groupBy<T>(elements: T[], by: (element: T) => string) {
return elements.reduce<{[name: string]: T[]}>((map, element) => {
const id = by(element)
if (check.isUndefined(map[id])) map[id] = []
map[id].push(element)
return map
}, {})
}

export function toList<T>(data: T | T[] | undefined): T[] {
if (check.isUndefined(data)) return []
if (Array.isArray(data)) return data
return [data]
}

export function firstValue<V>(map: {[key: string]: V}): V {
return Object.values(map).values().next().value
}

export function firstKey<V>(map: {[key: string]: V}): string {
return Object.keys(map).values().next().value
}

export function firstEntry<V>(map: {[key: string]: V}): [string, V] {
return Object.entries(map)[0]
}

export function isEmpty(obj: any) {
if (check.isUndefined(obj)) return true
if (check.isArray(obj)) return obj.length === 0
if (check.isObject(obj)) return Object.keys(obj).length === 0
throw new Error(`Can not check if obj ${pretty(obj)} is empty`)
}

export function last<T>(array: T[]) {
return array[array.length - 1]
}

export function listDelete<T>(list?: Array<T>, indexes?: Array<number>) {
if (check.isUndefined(list) || check.isUndefined(indexes)) return
indexes.sort()
while (indexes.length) {
const index = indexes.pop()
if (check.isUndefined(index)) return
list.splice(index, 1)
}
}

export function copy<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj)) as T
}

export function pretty(obj: any) {
return JSON.stringify(obj, null, 4)
Expand All @@ -73,94 +8,11 @@ export function stringify(obj: any) {
return JSON.stringify(obj)
}

export function joinNotNull(array: (string | undefined)[], separator = ' ') {
return filterNotNull(array).join(separator)
}

export function filterNotNull<T>(array: any[]): T[] {
return array.filter(x => x !== undefined && x !== null)
}

export function prettyBytes(bytes?: number) {
if (bytes === undefined) return
const kb = bytes / 1000
const mb = kb / 1000
return kb > 1000 ? `${prettyNumber(mb)} mb` : `${prettyNumber(Math.round(kb))} kb`
}

export function prettyMilliseconds(ms?: number) {
if (ms === undefined) return
const s = ms / 1000
return ms > 1000 ? `${s.toFixed(3)} s` : `${ms.toFixed(3)} ms`
}

export function prettyNumber(number?: number) {
if (number === undefined) return
if (Number.isInteger(number)) return number.toLocaleString('en')
return number.toLocaleString('en', {maximumFractionDigits: 3, minimumFractionDigits: 3})
}

export function getMedianFromSorted(array: number[]) {
const mid = Math.floor(array.length / 2)
return array.length % 2 ? array[mid] : (array[mid] + array[mid - 1]) / 2
}

export function toBoolean(data: string | boolean) {
return data === 'true' || data === true
}

export function hrtime2ms(data: [number, number]) {
return (data[0] * 1000000000 + data[1]) / 1000000
}

export function normalizeString(value: string) {
return value.toLowerCase().replaceAll(' ', '_')
}

export async function sleep(ms = 1000) {
return new Promise(resolve => setTimeout(resolve, ms))
}

export function toFixed(value: number) {
return Number(value.toFixed(2))
}

export function toFirstUpperCase(value: string) {
return value.charAt(0).toUpperCase() + value.slice(1)
}

export function sumObjects(objects: {[key: string]: number}[]) {
return objects.reduce((a, b) => {
for (const key in b) {
// eslint-disable-next-line no-prototype-builtins
if (b.hasOwnProperty(key)) a[key] = (a[key] || 0) + b[key]
}
return a
}, {})
}

export function looseParse(value: any) {
try {
return JSON.parse(value)
} catch (e) {
return value
}
}

export function getPrefixedEnv(prefix: string) {
return Object.entries(process.env).reduce<{[key: string]: any}>((acc, [key, value]) => {
if (!check.isDefined(value)) return acc
if (!key.startsWith(prefix)) return acc

const name = key.slice(prefix.length).toLowerCase()
const parsed = looseParse(value)

acc[name] = parsed
return acc
}, {})
}

export function createOutsidePromise() {
export function createDecomposedPromise() {
let _resolve: (value: void | PromiseLike<void>) => void
let _reject: (reason?: any) => void

Expand Down
1 change: 0 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"#/*": ["src/*"],
"#utils/*": ["src/utils/*"],
"#files": ["src/utils/files"],
"#crypto": ["src/utils/crypto"],
"#utils": ["src/utils/utils"],
"#check": ["src/utils/check"],
"#assert": ["src/utils/assert"],
Expand Down
Loading

0 comments on commit 340810f

Please sign in to comment.