Skip to content

Commit

Permalink
✨ Add init function
Browse files Browse the repository at this point in the history
Closes #112
  • Loading branch information
TomokiMiyauci committed Jun 28, 2021
1 parent 76387ba commit db20f47
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2021-present the Fonction authors. All rights reserved. MIT license.
import { slice } from './slice.ts'
/**
* Returns all but the last element of the given list or string.
*
* @param val - string or any array object
* @returns The result of `val.slice(0, -1)`
*
* @example
* ```ts
* // String
* init('hello') // 'hell'
* init('h') // ''
* init('') // ''
* ```
*
* @example
* ```ts
* init([1, 2, 3]) // [1, 2]
* init(['hello', 'world']) // ['hello']
* init(['hello']) // []
* init([]) // []
* ```
*
* @category `Array` `String`
*
* @see Related to {@link tail}
*
* @public
*/
const init: {
(val: string): string
<T extends unknown[]>(val: T): T
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} = (val: any) => slice(0, -1, val)

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

Deno.test('init', () => {
const tableString: [string, string][] = [
['', ''],
['a', ''],
['ab', 'a'],
['abc', 'ab']
]
tableString.forEach(([val, expected]) => {
assertEquals(init(val), expected, `init(${val}) -> ${expected}`)
})

const tableArray: [unknown[], unknown[]][] = [
[[], []],
[[''], []],
[[undefined], []],
[[null], []],
[[0], []],
[['', ''], ['']],
[[0, 0], [0]],
[[0, ''], [0]],
[['hello', 'world'], ['hello']],
[
['hello', 'new', 'world'],
['hello', 'new']
],
[
[undefined, null, 'hello', 'world'],
[undefined, null, 'hello']
],
[[['hello', 'world']], []]
]

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

0 comments on commit db20f47

Please sign in to comment.