-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refactoring "patch.ts" #108
Comments
Function replace() has a problem that the same file can be loaded & saved multiple times. {
const
path = 'types/p5/src/events/mouse.d.ts',
swapL = '(event?: ',
swapR = 'Event): false | void;';
for (const [ func, evt ] of [
[ 'mouseMoved', 'Mouse' ],
[ 'mouseDragged', 'Drag' ],
[ 'mousePressed', 'Mouse' ],
[ 'mouseReleased', 'Mouse' ],
[ 'mouseClicked', 'Mouse' ],
[ 'doubleClicked', 'Mouse' ],
[ 'mouseWheel', 'Wheel' ]
]) replace(path, func + WHAT, func + swapL + evt + swapR);
} For such cases where multiple change calls are made for the same file path, I've split helper function replace() into 3 parts: replaceOpen(), replaceData() & replaceClose() import { readFileSync, writeFileSync } from 'node:fs';
const
UTF8 = { encoding: 'utf8' } as const,
WHAT = '(event?: object): void;';
function replaceOpen(path: string | URL) {
try {
return readFileSync(path, UTF8);
} catch (err) { return console.error(err), ''; }
}
function replaceData(content: string, what: string, swap: string) {
const altered = content.replace(what, swap);
if (altered == content) console.error(
`"${ what }"\nnot found when attempting:\n"${ swap }"\n`
);
return altered;
}
function replaceClose(path: string | URL, content: string) {
try {
return writeFileSync(path, content), true;
} catch (err) { return console.error(err), false; }
} Compare the previous loop example w/ this 1 using the split replace() functions instead: {
const
path = 'types/p5/src/events/mouse.d.ts',
swapL = '(event?: ',
swapR = 'Event): false | void;';
let content = replaceOpen(path);
if (content) for (const [ func, evt ] of [
[ 'mouseMoved', 'Mouse' ],
[ 'mouseDragged', 'Drag' ],
[ 'mousePressed', 'Mouse' ],
[ 'mouseReleased', 'Mouse' ],
[ 'mouseClicked', 'Mouse' ],
[ 'doubleClicked', 'Mouse' ],
[ 'mouseWheel', 'Wheel' ]
]) content = replaceData(content, func + WHAT, func + swapL + evt + swapR);
content && replaceClose(path, content);
} Now file path 'types/p5/src/events/mouse.d.ts' is loaded once, its content is changed 7 times, and then saved once at the end. |
Just letting you know I'm doing lotsa refactoring on "patch.ts".
Here's a preview of it:
Lemme know what you think. ^_^
The text was updated successfully, but these errors were encountered: