Skip to content

Commit

Permalink
Fix lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
queicherius committed Dec 2, 2024
1 parent 046d24c commit 1a17e12
Show file tree
Hide file tree
Showing 30 changed files with 109 additions and 95 deletions.
8 changes: 4 additions & 4 deletions src/benchmarkHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,20 @@ export class Benchmark {
this.results = []
}

add(options: BenchmarkSample) {
add(options: BenchmarkSample): void {
this.suite.add(options.library + ' | ' + options.input, options.func)
}

run() {
run(): void {
this.suite.on('cycle', (event: Event) => this.addResult(event))
this.suite.on('complete', () => this.writeResults())
this.suite.run({ async: true })
}

// Parse the string output of BenchmarkJS because that seems easier than trying
// to understand their API and doing all the calculations ourselves...
addResult(event: Event) {
const eventString = String(event.target)
addResult(event: Event): void {
const eventString = String(event.target) // eslint-disable-line @typescript-eslint/no-base-to-string

const [name, runtimeInfo] = eventString.split(' x ')
const [library, input] = name.split(' | ')
Expand Down
2 changes: 1 addition & 1 deletion src/clone/clone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ import { JSONValue } from '../typeHelpers'
*/

export function clone<T extends JSONValue>(value: T): T {
return JSON.parse(JSON.stringify(value))
return JSON.parse(JSON.stringify(value)) as T
}
6 changes: 3 additions & 3 deletions src/debounce/debounce.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('debounce', () => {
expect(func.mock.calls).toEqual([['abcd'], ['abcde']])
})

test('has the correct type', async () => {
test('has the correct type', () => {
const func = (a: number, b: number): number => {
return a + b
}
Expand All @@ -34,9 +34,9 @@ describe('debounce', () => {
debouncedFunc(2, 'a')

// @ts-expect-error The return value is void
debouncedFunc(2, 2)?.concat
debouncedFunc(2, 2)?.concat()

// @ts-expect-error The return value is void
debouncedFunc(2, 2)?.toFixed
debouncedFunc(2, 2)?.toFixed()
})
})
11 changes: 8 additions & 3 deletions src/debounce/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@ import { TAnyFunction } from '../typeHelpers'
* ```
*/

export function debounce<TFunc extends TAnyFunction<void>>(func: TFunc, wait: number) {
type FunctionWithVoidReturn<TFunc extends TAnyFunction<void>> = (...args: Parameters<TFunc>) => void

export function debounce<TFunc extends TAnyFunction<void>>(
func: TFunc,
wait: number
): FunctionWithVoidReturn<TFunc> {
let timeoutID: NodeJS.Timeout | null = null

return function (this: unknown, ...args: unknown[]) {
timeoutID && clearTimeout(timeoutID)
if (timeoutID) clearTimeout(timeoutID)
timeoutID = setTimeout(() => func.apply(this, args), wait)
} as (...args: Parameters<TFunc>) => void
} as FunctionWithVoidReturn<TFunc>
}
6 changes: 4 additions & 2 deletions src/flatten/flatten.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ type Collapse<T extends Entry> = {

type FlattenObject<T> = Collapse<Explode<T>>

export function flatten<TObject extends Record<string, unknown>>(object: TObject) {
export function flatten<TObject extends Record<string, unknown>>(
object: TObject
): FlattenObject<TObject> {
const result: Record<string, unknown> = {}

function recurse(current: Record<string, unknown>, prefix = '') {
function recurse(current: Record<string, unknown>, prefix = ''): void {
for (const key in current) {
const value = current[key]
const nextKey = prefix ? `${prefix}.${key}` : key
Expand Down
6 changes: 4 additions & 2 deletions src/generateDocs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const END_TOKEN = '<!-- END GENERATED FROM FILES -->'

run().catch((err) => console.error(err))

async function run() {
async function run(): Promise<void> {
// Parse the module documentations
let modules = parseModules().sort((a, b) => a.name.localeCompare(b.name))

Expand Down Expand Up @@ -50,7 +50,9 @@ async function run() {
fs.writeFileSync('./README.md', README, 'utf-8')
}

async function calculateModuleSizes(name: string) {
async function calculateModuleSizes(
name: string
): Promise<{ size: string; minSize: string; minZipSize: string }> {
const content = fs.readFileSync(path.join(__dirname, `../dist/esm/${name}/${name}.js`), 'utf-8')

const contentMin = (await terser.minify(content)).code || ''
Expand Down
4 changes: 2 additions & 2 deletions src/get/get.benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ const benchmark = new Benchmark('get')
benchmark.add({
library: 'lodash',
input: 'array path',
func: () => lodash.get(OBJECT, ['foo', 'bar', 'herp' + Math.random()]),
func: (): unknown => lodash.get(OBJECT, ['foo', 'bar', 'herp' + Math.random()]),
})

benchmark.add({
library: 'lodash',
input: 'string path',
func: () => lodash.get(OBJECT, 'foo.bar.herp' + Math.random()),
func: (): unknown => lodash.get(OBJECT, 'foo.bar.herp' + Math.random()),
})

benchmark.add({
Expand Down
19 changes: 8 additions & 11 deletions src/get/get.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-explicit-any */

const REPLACE_EMPTY_REGEX = /]|^\[/g
const REPLACE_DOT_REGEX = /\.?\[/g

/**
* ### get(object, path, defaultValue?)
*
Expand All @@ -28,11 +22,14 @@ const REPLACE_DOT_REGEX = /\.?\[/g
* ```
*/

const REPLACE_EMPTY_REGEX = /]|^\[/g
const REPLACE_DOT_REGEX = /\.?\[/g

export function get(
object: object | null | undefined,
path: string | Array<string | number>,
defaultValue?: any
): any {
defaultValue?: unknown
): unknown {
// Handle the case that the object is undefined or not an object
if (!object || Object(object) !== object) {
return defaultValue
Expand All @@ -50,13 +47,13 @@ function parsePath(path: string): Array<string> {
return path.replace(REPLACE_EMPTY_REGEX, '').replace(REPLACE_DOT_REGEX, '.').split('.')
}

function getWithArrayPath(object: object, path: Array<string | number>): any {
function getWithArrayPath(object: object, path: Array<string | number>): unknown {
const length = path.length
let index = 0
let current: any = object
let current = object as Record<string | number, unknown> | null

while (current != null && index < length) {
current = current[path[index++]]
current = current[path[index++]] as Record<string | number, unknown> | null
}

return index === length ? current : undefined
Expand Down
2 changes: 1 addition & 1 deletion src/hash/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export function hash(data: JSONValue): string {
}

// Multiply two 32-bit numbers
function mul32(m: number, n: number) {
function mul32(m: number, n: number): number {
const nLow = n & 0xffff
const nHigh = n - nLow

Expand Down
12 changes: 9 additions & 3 deletions src/matchAll/matchAll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,20 @@
* ```
*/

export function matchAll(regExp: RegExp, string: string) {
export interface MatchAllMatch {
match: string
subMatches: Array<string>
index: number
}

export function matchAll(regExp: RegExp, string: string): Array<MatchAllMatch> {
return Array.from(string.matchAll(regExp)).map(formatMatch)
}

function formatMatch(match: RegExpMatchArray) {
function formatMatch(match: RegExpMatchArray): MatchAllMatch {
return {
match: match[0],
subMatches: match.slice(1, match.length),
index: match.index,
index: match.index!,
}
}
6 changes: 3 additions & 3 deletions src/memoize/memoize.benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import lodash from 'lodash'
import { Benchmark } from '../benchmarkHelper'
import { memoize } from './memoize'

function monadicPrimitiveFunc(a: number) {
function monadicPrimitiveFunc(a: number): number {
return a + 1
}

function monadicSerializedFunc(a: string) {
function monadicSerializedFunc(a: string): string {
return a + '1'
}

function variadicFunc(a: number, b: number) {
function variadicFunc(a: number, b: number): number {
return a + b
}

Expand Down
35 changes: 18 additions & 17 deletions src/memoize/memoize.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ type NumberObject = { n: number }
describe('memoize', () => {
test('memoizes function calls with no arguments', () => {
const calls: Array<[]> = []
const func = () => {
const func = (): number => {
calls.push([])
return 1
}
Expand All @@ -20,7 +20,7 @@ describe('memoize', () => {

test('memoizes function calls with a single primitive argument', () => {
const calls: Array<Array<number>> = []
const func = (x: number) => {
const func = (x: number): number => {
calls.push([x])
return x + 1
}
Expand All @@ -36,7 +36,7 @@ describe('memoize', () => {

test('memoizes function calls with a single non-primitive argument', () => {
const calls: Array<Array<NumberObject>> = []
const func = (x: NumberObject) => {
const func = (x: NumberObject): number => {
calls.push([x])
return x.n + 1
}
Expand All @@ -52,7 +52,7 @@ describe('memoize', () => {

test('memoizes function calls with multiple primitive arguments', () => {
const calls: Array<Array<number>> = []
const func = (a: number, b: number) => {
const func = (a: number, b: number): number => {
calls.push([a, b])
return a + b
}
Expand All @@ -73,7 +73,7 @@ describe('memoize', () => {

test('memoizes function calls with multiple non-primitive arguments', () => {
const calls: Array<Array<NumberObject>> = []
const func = (a: NumberObject, b: NumberObject) => {
const func = (a: NumberObject, b: NumberObject): number => {
calls.push([a, b])
return a.n + b.n
}
Expand All @@ -94,7 +94,7 @@ describe('memoize', () => {

test('memoizes function calls with spread primitive arguments', () => {
const calls: Array<Array<number>> = []
const func = (multiplier: number, ...numbers: Array<number>) => {
const func = (multiplier: number, ...numbers: Array<number>): Array<number> => {
calls.push([multiplier, ...numbers])
return numbers.map((x) => multiplier * x)
}
Expand All @@ -114,7 +114,7 @@ describe('memoize', () => {

test('memoizes function calls with spread non-primitive arguments', () => {
const calls: Array<Array<NumberObject>> = []
const func = (multiplier: NumberObject, ...numbers: Array<NumberObject>) => {
const func = (multiplier: NumberObject, ...numbers: Array<NumberObject>): Array<number> => {
calls.push([multiplier, ...numbers])
return numbers.map((x) => multiplier.n * x.n)
}
Expand All @@ -133,7 +133,8 @@ describe('memoize', () => {
})

test('passes arguments as their original primitive', () => {
const func = (x: unknown) => (typeof x === 'object' && x ? x.constructor.name : typeof x)
const func = (x: unknown): string =>
typeof x === 'object' && x ? x.constructor.name : typeof x

const memoizedFunc = memoize(func)

Expand All @@ -144,7 +145,7 @@ describe('memoize', () => {

test('can define a custom strategy (monadic)', () => {
const calls: Array<Array<number>> = []
const func = (a: number, b: number) => {
const func = (a: number, b: number): number => {
calls.push([a, b])
return a
}
Expand All @@ -167,7 +168,7 @@ describe('memoize', () => {

test('can define a custom strategy (variadic)', () => {
const calls: Array<Array<number>> = []
const func = (x: number) => {
const func = (x: number): number => {
calls.push([x])
return x + 1
}
Expand All @@ -185,12 +186,12 @@ describe('memoize', () => {

test('can define a custom serializer', () => {
let serializerCalls = 0
function serializer(data: unknown) {
function serializer(data: unknown): string {
serializerCalls++
return '__' + JSON.stringify(data) + '__'
}

const func = (a: number, b: number) => {
const func = (a: number, b: number): number => {
return a + b
}

Expand All @@ -206,7 +207,7 @@ describe('memoize', () => {

test('memoizes function calls that return promises', async () => {
let calls = 0
const func = async () => {
const func = async (): Promise<string> => {
calls++
await sleep(10)
return 'A'
Expand All @@ -231,7 +232,7 @@ describe('memoize', () => {

test('memoizes function calls with a maximum TTL', async () => {
const calls: Array<Array<number>> = []
const func = (a: number, b: number) => {
const func = (a: number, b: number): number => {
calls.push([a, b])
return a + b
}
Expand Down Expand Up @@ -266,7 +267,7 @@ describe('memoize', () => {
'smartly memoizes function calls that return promise rejections (%s)',
async (_: string, options: MemoizeOptions) => {
let calls = 0
const func = async () => {
const func = async (): Promise<string> => {
calls++
await sleep(10)

Expand Down Expand Up @@ -297,7 +298,7 @@ describe('memoize', () => {
}
)

test('has the correct type', async () => {
test('has the correct type', () => {
const func = (a: number, b: number): number => {
return a + b
}
Expand All @@ -311,7 +312,7 @@ describe('memoize', () => {
memoizedFunc(2, 'a')

// @ts-expect-error The return value is a number
memoizedFunc(2, 2).concat
expect(() => memoizedFunc(2, 2).concat()).toThrow()

// This one is okay
memoizedFunc(2, 2).toFixed(2)
Expand Down
Loading

0 comments on commit 1a17e12

Please sign in to comment.