mysticsymbolic.github.io/lib/util.ts

100 wiersze
2.3 KiB
TypeScript
Czysty Zwykły widok Historia

export function float(value: string | number | undefined): number {
if (typeof value === "number") return value;
if (value === undefined) value = "";
const float = parseFloat(value);
if (isNaN(float)) {
throw new Error(`Expected '${value}' to be a float!`);
}
return float;
}
export function flatten<T>(arr: T[][]): T[] {
const result: T[] = [];
for (let subarr of arr) {
result.push(...subarr);
}
return result;
}
/**
* Convert radians to degrees.
*/
export function rad2deg(radians: number): number {
return (radians * 180) / Math.PI;
}
export type NumericInterval = {
min: number;
max: number;
};
export type NumericRange = NumericInterval & {
step: number;
};
/**
* Return numbers within the given range, inclusive.
*/
export function inclusiveRange({ min, max, step }: NumericRange): number[] {
const result: number[] = [];
for (let i = min; i <= max; i += step) {
result.push(i);
}
return result;
}
/**
* Return an array containing the numbers from 0 to one
* less than the given value, increasing.
*/
export function range(count: number): number[] {
return inclusiveRange({ min: 0, max: count - 1, step: 1 });
}
/**
* Slugify the given string.
*
* Taken from: https://gist.github.com/mathewbyrne/1280286
*/
export function slugify(text: string) {
return text
.toString()
.toLowerCase()
.replace(/\s+/g, "-") // Replace spaces with -
.replace(/[^\w\-]+/g, "") // Remove all non-word chars
.replace(/\-\-+/g, "-") // Replace multiple - with single -
.replace(/^-+/, "") // Trim - from start of text
.replace(/-+$/, ""); // Trim - from end of text
}
/** Returns whether the given number is even (as opposed to odd). */
export function isEvenNumber(value: number) {
return value % 2 === 0;
}
Always permalink to Mandalas. (#99) This addresses #61 by making mandalas permalinked. The URL to a mandala will change whenever the user stops fiddling with it for 250 ms. This means that the user can always reload the page to get a reasonably recent version of what they were creating, and they can use the browser's "back" and "next" buttons to effectively undo/redo recent changes. They can also copy the URL to share it with others. ## About the serialization format Originally, I stored the state of the user's mandala in the URL using JSON. This had a number of drawbacks, though: * **It was really long.** A mandala serialization was almost 1k characters, which was a very big URL, and one that some sharing platforms might even reject. * **It wasn't type-checked in any way.** Unless I added some kind of JSON schema validation (which I didn't), the serialization was simply deserialized and assumed to be in the proper format. This could result in confusing exceptions during render time, rather than decisively exploding at deserialization time. To resolve these limitations, and because I thought it would be fun, I decided to store the mandala state using a serialization format called [Apache Avro][]. I first read about this in Kleppmann's [Designing Data-Intensive Applications][kleppmann] and was intrigued by both its compactness (a serialized mandala is around 80-120 characters) and schema evolution properties. It might be going a bit overboard, but again, I thought it would be fun and I wanted to play around with Avro. Also, I tried architecting things in such a way that all the Avro code is in its own file, and can easily be removed (or swapped out for another serialization format) if we decide it's dumb. [Apache Avro]: http://avro.apache.org/ [kleppmann]: https://dataintensive.net/ ## Other changes This PR also makes a few other changes: * Tests can now import files with JSX in them (I don't think this was required for the final state of this PR, but I figured I'd leave it in there for its almost inevitable use in the future). * The value labels for number sliders now have a fixed width, which eliminates a weird "jitter" effect that sometimes occurred when using them.
2021-04-24 12:46:32 +00:00
/**
* Convert the given number of seconds (float) to milliseconds (integer).
*/
export function secsToMsecs(secs: number): number {
return Math.floor(secs * 1000);
}
/**
* Returns the given number to a "friendly-looking" human
* representation that is not ridiculously long. For example,
* it will return "1.85" instead of "1.850000000143".
*/
export function toFriendlyDecimal(value: number, maxDecimalDigits = 2): string {
const str = value.toString();
const fixedStr = value.toFixed(maxDecimalDigits);
return str.length < fixedStr.length ? str : fixedStr;
}