Created
May 10, 2020 08:17
-
-
Save flxxyz/206964233801b5ef8e3020c1eb173588 to your computer and use it in GitHub Desktop.
一些ts的奇怪用法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//枚举的使用 | |
enum OSName { | |
windows, | |
darwin, | |
linux, | |
centos, | |
fedora, | |
debian, | |
ubuntu, | |
suse, | |
freebsd, | |
unknown, | |
} | |
interface OS { | |
name: OSName; | |
version: string; | |
arch: string; | |
} | |
const os: Array<OS>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//这样定义一个接口太方便了 | |
interface Map { | |
[key: string]: any, | |
[index: number]: any, | |
} | |
const base = 1024; | |
const unitSize: Map = { | |
P: base ** 5, | |
T: base ** 4, | |
G: base ** 3, | |
M: base ** 2, | |
K: base, | |
B: 1, | |
}; | |
//计算字节大小已直观的文本显示 | |
function byteUnit(bytes: number): string { | |
bytes = bytes || 0; | |
if (bytes === 0) { | |
return '0B'; | |
} | |
const keys = Object.keys(unitSize); | |
const values = Object.values(unitSize); | |
for (let i = 0; i < keys.length; i += 1) { | |
const key = keys[i]; | |
const value = values[i]; | |
const n = bytes / value; | |
const c = Math.floor(n); | |
if (c !== 0) { | |
return `${Math.round(n)}${key}`; | |
} | |
} | |
return '0B'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment