简体   繁体   English

TypeScript中的“功能”常量枚举

[英]“Functional” const enum in TypeScript

I'm working on the color scheme of a React application (w/ CSS-in- JS TS), and, for convenience, I write the colors using HSL, but, since they are quite a lot, I would like to deliver them to the users as hex to save some unnecessary bytes. 我正在研究React应用程序的配色方案(带有CSS-in- JS TS),为方便起见,我使用HSL编写了颜色,但是由于它们很多,所以我想提供它们以十六进制形式发送给用户,以节省一些不必要的字节。 I am now faced with two options: 我现在面临两个选择:

  • either I do something like this: 我要么做这样的事情:
const hsl = (h: number, s: number, l: number) => {
  /* convert to hex */
  return hex;
}

const colors = {
  primary: hsl(205, 1, 0.52)
}

but this approach would (1) go against my point of saving bytes and (2) require the colors to be recalculated each and every time, 但是这种方法(1)违反了我保存字节的观点,并且(2)每次都需要重新计算颜色,

  • or I just write down the HSL values somewhere else, and put hex codes in my code. 或者我只是在其他地方写下HSL值,然后将十六进制代码放在我的代码中。

I found that the nearest thing to what I want to do are TypeScript's const enum s, which replace values at compile time. 我发现与我想做的最接近的事情是TypeScript的const enum ,它在编译时替换值。 However, they only store predefined values, and can't – to my knowledge – be used as a function. 但是,它们仅存储预定义的值,并且-据我所知-不能用作函数。 So, I would need to be able to do something like this: 因此,我需要能够执行以下操作:

const enum Hsl (h: number, s: number, l: number) {
  /* convert to hex */
  return hex;
}

const colors = {
  primary: Hsl(205, 1, 0.52)
}

which would get compiled to 这将被编译为

const colors = {
  primary: '#0C9BFF'
};

How could I achieve this? 我怎样才能做到这一点?

ᶦˢ ᵗʰᶦˢ ᵉᵛᵉⁿ ᵖᵒˢˢᶦᵇˡᵉˀ ᶦˢᵗʰᶦˢᵉᵛᵉⁿᵖᵒˢˢᶦᵇˡᵉˀ

An alternative I considered was using the first approach and then letting tools like Prepack do some optimizations (pre-evaluating the function and removing it). 我考虑的替代方法是使用第一种方法,然后让诸如Prepack之类的工具进行一些优化(预评估功能并将其删除)。

What you need is some form of caching mechanism. 您需要某种形式的缓存机制。

You first generate a unique id based on the input, eg 您首先根据输入生成唯一的ID,例如

function getId(h: number, s: number, l: number) {
   return String(h) + ',' + String(s) + ',' + String(l)
}

and then cache the value as you go: 然后随身缓存值:

const cache: Record<string, string> = {}
function hsl(h: number, s: number, l: number) {
  const id = getId(h, s, l)
  return cache[id] = /* do your calculation */
}

With that, as you fill in your predefined colors , the value will be cached and you don't need to re-calculate it. 这样,当您填充预定义的colors ,该值将被缓存,而无需重新计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM