Skip to content

Commit db20f47

Browse files
committed
✨ Add init function
Closes #112
1 parent 76387ba commit db20f47

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

src/init.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright 2021-present the Fonction authors. All rights reserved. MIT license.
2+
import { slice } from './slice.ts'
3+
/**
4+
* Returns all but the last element of the given list or string.
5+
*
6+
* @param val - string or any array object
7+
* @returns The result of `val.slice(0, -1)`
8+
*
9+
* @example
10+
* ```ts
11+
* // String
12+
* init('hello') // 'hell'
13+
* init('h') // ''
14+
* init('') // ''
15+
* ```
16+
*
17+
* @example
18+
* ```ts
19+
* init([1, 2, 3]) // [1, 2]
20+
* init(['hello', 'world']) // ['hello']
21+
* init(['hello']) // []
22+
* init([]) // []
23+
* ```
24+
*
25+
* @category `Array` `String`
26+
*
27+
* @see Related to {@link tail}
28+
*
29+
* @public
30+
*/
31+
const init: {
32+
(val: string): string
33+
<T extends unknown[]>(val: T): T
34+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
35+
} = (val: any) => slice(0, -1, val)
36+
37+
export { init }

test/init.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Copyright 2021-present the Fonction authors. All rights reserved. MIT license.
2+
import { assertEquals } from '../dev_deps.ts'
3+
import { init } from '../src/init.ts'
4+
5+
Deno.test('init', () => {
6+
const tableString: [string, string][] = [
7+
['', ''],
8+
['a', ''],
9+
['ab', 'a'],
10+
['abc', 'ab']
11+
]
12+
tableString.forEach(([val, expected]) => {
13+
assertEquals(init(val), expected, `init(${val}) -> ${expected}`)
14+
})
15+
16+
const tableArray: [unknown[], unknown[]][] = [
17+
[[], []],
18+
[[''], []],
19+
[[undefined], []],
20+
[[null], []],
21+
[[0], []],
22+
[['', ''], ['']],
23+
[[0, 0], [0]],
24+
[[0, ''], [0]],
25+
[['hello', 'world'], ['hello']],
26+
[
27+
['hello', 'new', 'world'],
28+
['hello', 'new']
29+
],
30+
[
31+
[undefined, null, 'hello', 'world'],
32+
[undefined, null, 'hello']
33+
],
34+
[[['hello', 'world']], []]
35+
]
36+
37+
tableArray.forEach(([val, expected]) => {
38+
assertEquals(init(val), expected, `init(${val}) -> ${expected}`)
39+
})
40+
})

0 commit comments

Comments
 (0)