-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathempty.ts
39 lines (31 loc) · 1.04 KB
/
empty.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Copyright (c) 2020 Jozty. All rights reserved. MIT license.
import { isArguments, isArray, isObject, isString } from './utils/is.ts';
import type { EmptyObj } from './utils/types.ts';
type EmptyReturnType<T> = T extends (infer U)[] ? U[]
: T extends string ? ''
: T extends EmptyObj ? EmptyObj
: T;
/**
* Returns the empty value of its argument's type.
*
* Fae.empty([1, 2, 3]) //=> []
* Fae.empty('unicorns') //=> ''
* Fae.empty({x: 1, y: 2}) //=> {}
*/
export function empty<T>(x: T): EmptyReturnType<T> {
if (x === null || x === undefined) return x as EmptyReturnType<T>;
// @ts-ignore: types handled by EmptyReturnType
if (isArray(x)) return [];
// @ts-ignore: types handled by EmptyReturnType
if (isString(x)) return '';
// @ts-ignore: types handled by EmptyReturnType
if (isObject(x)) return {};
if (isArguments(x)) {
// @ts-ignore: types handled by EmptyReturnType
return (function () {
return arguments;
})();
}
// @ts-ignore: types handled by EmptyReturnType
return null;
}