Skip to content

Instantly share code, notes, and snippets.

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 rwaldron/1cb432df9a88fe7d2220966e43ef8d6d to your computer and use it in GitHub Desktop.
Save rwaldron/1cb432df9a88fe7d2220966e43ef8d6d to your computer and use it in GitHub Desktop.
// https://www.w3.org/TR/css-typed-om-1/#simple-numeric
class CSSUnitValue {
constructor(value, unit) {
this.value = value;
this.unit = unit;
}
toString() {
// https://www.w3.org/TR/css-typed-om-1/#numericvalue-serialization
// 4. Otherwise, if unit is "percentage", append "%" to s, then return s.
return `${this.value}${this.unit === "percent" ? "%" : ""}`;
}
}
// https://www.w3.org/TR/css-typed-om-1/#numeric-factory
const CSS = {
px(value) {
return new CSSUnitValue(value, "px");
},
percent(value) {
return new CSSUnitValue(value, "percent");
}
};
function px({ number }) {
return CSS.px(number);
}
function percent({ number }) {
return CSS.percent(number);
}
// 1percent
console.log(String(percent(Object.freeze({ number: 1, string: "1" })))); // "1%"
// 1px
console.log(String(px(Object.freeze({ number: 1, string: "1" })))); // "1"
let a = px(Object.freeze({ number: 1, string: "1" }));
let b = px(Object.freeze({ number: 3, string: "3" }));
console.log(
a + b // "13"
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment