-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Cache expensive Typst operations for quick iterations during development
- Loading branch information
Showing
4 changed files
with
84 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import {hash} from "./hash.ts"; | ||
|
||
const cacheKeys = new Map<string, string>(); | ||
|
||
/** | ||
* Check if the content of a file has changed since the last time it was checked. | ||
* Stores the hash of the content in a cache to compare it later. | ||
* | ||
* @param path the path to the file | ||
* @param content the content of the file | ||
* @returns an object with the cache key and a boolean indicating if the content has changed since the last time it was checked | ||
* | ||
* @example | ||
* ```ts | ||
* const {cacheKey, shouldRecompile} = checkForChanges( | ||
* "file.txt", | ||
* "Hello, world!" | ||
* ); | ||
* | ||
* if (shouldRecompile) { | ||
* // Recompile the file | ||
* // ... | ||
* } | ||
* console.log("The cache key is", cacheKey); | ||
* ``` | ||
*/ | ||
export function checkForChanges(path: string, content: string) { | ||
const cacheKey = hash(content) | ||
const shouldRecompile = cacheKeys.get(path) !== cacheKey; | ||
cacheKeys.set(path, cacheKey); | ||
return {cacheKey, shouldRecompile}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
/** | ||
* Hash a string | ||
* @param s | ||
*/ | ||
export function hash(s: string) { | ||
let hash = 0; | ||
for (let i = 0; i < s.length; i++) { | ||
hash = ((hash << 5) - hash) + s.charCodeAt(i); | ||
hash |= 0; | ||
} | ||
return hash.toString(16); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters