Skip to content

Commit

Permalink
🐛 Fix types of length function
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jun 12, 2021
1 parent 6bf050f commit 5683d6a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
9 changes: 4 additions & 5 deletions src/length.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
// Copyright 2021-present the Fonction authors. All rights reserved. MIT license.
/**
* Returns the number of elements in the array or string length.
* Returns length property.
*
* @param val - `string` or any `array`
* @param val - Value with length property
* @returns The result of `val.length`
*
* @example
* ```ts
* length('hello') // 5
* length(['hello', 'world', 1]) // 3
* length({length: 5, text: 'hello'}) // 5
* ```
*
* @category `Array` `String`
*
* @public
*/
const length = <T extends unknown[] | string>(val: T): T['length'] => val.length
const length = <T extends { length: number }>(val: T): T['length'] => val.length

export { length }
11 changes: 9 additions & 2 deletions test/length.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// Copyright 2021-present the Fonction authors. All rights reserved. MIT license.
import { assertEquals } from '../dev_deps.ts'
import { length } from '../src/length.ts'
import { assertEqual } from './asserts.ts'

Deno.test('length', () => {
const table: [unknown[] | string, number][] = [
const table: [{ length: number } | string, number][] = [
['', 0],
[' ', 1],
[' ', 2],
Expand All @@ -13,10 +14,16 @@ Deno.test('length', () => {
[[], 0],
[[''], 1],
[['', 0], 2],
[['', 0, '1'], 3]
[['', 0, '1'], 3],
[{ length: 3 }, 3]
]

table.forEach(([val, expected]) => {
assertEquals(length(val), expected, `length(${val}) -> ${expected}`)
})

assertEqual<number>(length(''))
assertEqual<number>(length([]))
assertEqual<number>(length({ length: 1 }))
assertEqual<1>(length({ length: 1 } as const))
})

0 comments on commit 5683d6a

Please sign in to comment.