Skip to content

Instantly share code, notes, and snippets.

@flxxyz

flxxyz/enum.ts

Created May 10, 2020
Embed
What would you like to do?
一些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
You can’t perform that action at this time.