Skip to content

Instantly share code, notes, and snippets.

@flxxyz
Created May 10, 2020 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flxxyz/206964233801b5ef8e3020c1eb173588 to your computer and use it in GitHub Desktop.
Save flxxyz/206964233801b5ef8e3020c1eb173588 to your computer and use it in GitHub Desktop.
一些ts的奇怪用法
//枚举的使用
enum OSName {
windows,
darwin,
linux,
centos,
fedora,
debian,
ubuntu,
suse,
freebsd,
unknown,
}
interface OS {
name: OSName;
version: string;
arch: string;
}
const os: Array<OS>;
//这样定义一个接口太方便了
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