-
Notifications
You must be signed in to change notification settings - Fork 20
/
lang.ts
46 lines (43 loc) · 1.43 KB
/
lang.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
40
41
42
43
44
45
46
export function isValidIdentifier (str: string) {
return !!/^[a-zA-Z_$][\w$]*$/.exec(str)
}
export function getMember<T> (clazz: Function, property: string, defaultValue: T): T
export function getMember<T> (clazz: Function, property: string): T | undefined
export function getMember<T> (clazz: Function, property: string, defaultValue?: T): T | undefined {
if (clazz[property] !== undefined) return clazz[property]
if (clazz.prototype && clazz.prototype[property] !== undefined) {
return clazz.prototype[property]
}
return defaultValue
}
export function functionString (fn: Function) {
let str = fn.toString()
if (!/^\s*function(\s|\()/.test(str) && /^\s*\w+\s*\([^)]*\)\s*{/.test(str)) { // es6 method syntax: foo(){}
str = 'function ' + str
}
/**
* 去除函数外缩进。例如:
*
* Input:
* function() {
* console.log(1)
* return 1
* }
*
* Output:
* function() {
* console.log(1)
* return 1
* }
*/
const lines = str.split('\n')
const firstLine = lines.shift()!
const minIndent = lines.reduce(
(min: number, line: string) => Math.min(min, /^\s*/.exec(line)![0].length),
Infinity
)
return [firstLine, ...lines.map(line => line.slice(minIndent))].join('\n')
}
export function assertNever (arg: never) {
throw new Error(`"${JSON.stringify(arg)}" not supported`)
}