Skip to content

Commit

Permalink
Use const instead of let where possible (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
lynn authored Jan 1, 2025
1 parent 487104e commit 7f57a0c
Show file tree
Hide file tree
Showing 11 changed files with 120 additions and 118 deletions.
46 changes: 23 additions & 23 deletions core/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,17 @@ export function call(
ret: (response: ApiResponse) => any,
uname?: string,
) {
let time = +new Date();
let action = actions.hasOwnProperty(i.action) && actions[i.action];
const time = +new Date();
const action = actions.hasOwnProperty(i.action) && actions[i.action];
if (!action) {
console.log(`%% action '${i.action}' unknown`);
return ret(flip('unknown action'));
}
if (!uname && 'token' in i && typeof i.token === 'string') {
let token = store.pass.tokens[i.token];
const token = store.pass.tokens[i.token];
if (token) {
uname = token.name;
let now = +new Date();
const now = +new Date();
if (now > token.last + config().token_expiry) {
delete store.pass.tokens[i.token];
ret = (old_ret => data => {
Expand All @@ -59,7 +59,7 @@ export function call(
} else store.pass.tokens[i.token].last = now;
}
}
let entries = Object.entries(i)
const entries = Object.entries(i)
.filter(
([k, v]) =>
Object.keys({ ...(action.checks || {}), uname: uname }).includes(k) &&
Expand All @@ -83,7 +83,7 @@ export function call(
if (!store.db) store.db = { entries: [] };
if (!store.pass) store.pass = { hashes: {}, tokens: {} };

let actions: Record<string, Action> = {};
const actions: Record<string, Action> = {};

const flip = (e: string): ApiError => ({ success: false, error: e });
const good = (d?: ApiBody): ApiResponse => ({ success: true, ...d });
Expand All @@ -95,11 +95,11 @@ function guard(
conds: Record<string, Check>,
f: ActionFunction,
): Action {
let res: any = (ret, i: object, uname: string | undefined) => {
const res: any = (ret, i: object, uname: string | undefined) => {
if (logged_in && !uname) return ret(flip('must be logged in'));
if (conds)
for (let [k, v] of Object.entries(conds)) {
let err = v(i[k]);
for (const [k, v] of Object.entries(conds)) {
const err = v(i[k]);
if (err !== true) return ret(flip(`invalid field '${k}'${`: ${err}`}`));
}
f(ret, i, uname);
Expand Down Expand Up @@ -164,7 +164,7 @@ actions.search = guard(
preferred_scope_bias: checks.optional(checks.number),
},
(ret, i, uname) => {
let data = search.search(i, uname);
const data = search.search(i, uname);
if (typeof data === 'string') ret(flip(data));
else ret(good({ results: data }));
},
Expand All @@ -181,8 +181,8 @@ actions.vote = guard(
vote: _ => [-1, 0, 1].includes(_) || 'invalid vote',
},
(ret, i, uname) => {
let e = by_id(i.id);
let old_vote = e.votes[uname] || 0;
const e = by_id(i.id);
const old_vote = e.votes[uname] || 0;
e.votes[uname] = i.vote;
e.score += i.vote - old_vote;
ret(good({ entry: present(e, uname) }));
Expand All @@ -197,8 +197,8 @@ actions.note = guard(
content: checks.nobomb,
},
(ret, i, uname) => {
let word = by_id(i.id);
let this_note = {
const word = by_id(i.id);
const this_note = {
date: new Date().toISOString(),
user: uname,
content: replacements(i.content),
Expand All @@ -217,7 +217,7 @@ actions.edit = guard(
scope: checks.scope,
},
(ret, i, uname) => {
let word = by_id(i.id);
const word = by_id(i.id);
if (word.user !== uname) {
return ret(flip('you are not the owner of this entry'));
}
Expand All @@ -242,9 +242,9 @@ actions.removenote = guard(
date: checks.present,
},
(ret, i, uname) => {
let word = by_id(i.id);
let keep = [];
let removed_notes = [];
const word = by_id(i.id);
const keep = [];
const removed_notes = [];
for (const note of word.notes) {
if (note.user === uname && note.date === i.date) {
removed_notes.push(note);
Expand Down Expand Up @@ -274,8 +274,8 @@ actions.create = guard(
scope: checks.scope,
},
(ret, i, uname) => {
let id = shortid.generate();
let this_entry: Entry = {
const id = shortid.generate();
const this_entry: Entry = {
id,
date: new Date().toISOString(),
head: shared.normalize(i.head),
Expand All @@ -299,7 +299,7 @@ actions.login = guard(
pass: checks.present,
},
(ret, i) => {
let expected = store.pass.hashes[i.name];
const expected = store.pass.hashes[i.name];
if (!expected) return ret(flip('user not registered'));
if (bcrypt.compareSync(i.pass, expected)) {
var token = uuid.v4();
Expand Down Expand Up @@ -339,8 +339,8 @@ actions.remove = guard(
id: checks.goodid,
},
(ret, i, uname) => {
let index = index_of(i.id);
let entry = store.db.entries[index];
const index = index_of(i.id);
const entry = store.db.entries[index];
if (entry.user !== uname)
return ret(flip('you are not the owner of this entry'));
store.db.entries.splice(index, 1);
Expand Down
16 changes: 8 additions & 8 deletions core/commons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ import { EventEmitter } from 'events';
const old_log = console.log;

export function log(...args: any[]): void {
let date = new Date()
const date = new Date()
.toISOString()
.replace(/[:-]/g, '')
.replace('T', '.')
.substring(4, 15);
let message = Array.from(args)
const message = Array.from(args)
.join(' ')
// padding the message so that it doesn't interfere
// with the timestamp column:
Expand Down Expand Up @@ -52,26 +52,26 @@ export function deburrMatch(
(a: string, b: string) => a == b,
][mode];
let count = 0;
for (let w of what) if (where.some(y => predicate(w, y))) count++;
for (const w of what) if (where.some(y => predicate(w, y))) count++;
return count;
}

const real_setInterval = global.setInterval;
const real_clearInterval = global.clearInterval;

let interval_cache = [];
const interval_cache = [];
export function setInterval(
callback: (...args: any[]) => void,
ms?: number,
): NodeJS.Timer {
let this_one = real_setInterval(callback, ms).unref();
const this_one = real_setInterval(callback, ms).unref();
interval_cache.push(this_one);
return this_one;
}

export function clearInterval(i: string | number | NodeJS.Timeout): void {
real_clearInterval(i);
let index = interval_cache.indexOf(i);
const index = interval_cache.indexOf(i);
if (index !== -1) interval_cache.splice(index, 1);
}

Expand Down Expand Up @@ -111,7 +111,7 @@ const FluidConfig = {
};
Object.setPrototypeOf(FluidConfig, new EventEmitter());
export function fluid_config(fname: string) {
let f: any = () => {
const f: any = () => {
return f.cache;
};
f.fname = fname;
Expand All @@ -127,7 +127,7 @@ const MAIN_CONFIG = 'config/config.yml',
__dirname = dirname(fileURLToPath(import.meta.url)),
DEFAULT_CONFIG = `${__dirname}/../../config/defaults.yml`;
// initialise the global config file
let main_config = fluid_config(MAIN_CONFIG),
const main_config = fluid_config(MAIN_CONFIG),
default_config = yaml(readFileSync(DEFAULT_CONFIG));

export const config: any = () => ({ ...default_config, ...main_config() });
Expand Down
40 changes: 21 additions & 19 deletions core/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ export interface PresentedEntry extends Omit<Entry, 'votes'> {

// compute a few fields for faster processing
export function cacheify(e: Entry): CachedEntry {
let deburredHead = deburr(e.head);
let deburredBody = deburr(e.body);
let deburredNotes = e.notes.flatMap(({ content }) => deburr(content));
const deburredHead = deburr(e.head);
const deburredBody = deburr(e.body);
const deburredNotes = e.notes.flatMap(({ content }) => deburr(content));
return {
$: e,
id: e.id,
Expand Down Expand Up @@ -88,7 +88,7 @@ export function score(entry: Entry): number {

emitter.on('remove', (_, entry) => cache.splice(cached_index(entry.id), 1));
emitter.on('create', (_, entry) => cache.push(cacheify(entry)));
for (let k of ['vote', 'note', 'removenote', 'edit', 'move'])
for (const k of ['vote', 'note', 'removenote', 'edit', 'move'])
emitter.on(k, (_, entry) =>
cache.splice(cached_index(entry.id), 1, cacheify(entry)),
);
Expand All @@ -113,20 +113,20 @@ interface Operation {
build: (args: any[]) => (entry: CachedEntry) => boolean;
}

let operations: Record<string, Operation> = (search.operations = {
const operations: Record<string, Operation> = (search.operations = {
and: {
type: OperationType.Functor,
check: all_funcs,
build: args => entry => {
for (let a of args) if (!a(entry)) return false;
for (const a of args) if (!a(entry)) return false;
return true;
},
},
or: {
type: OperationType.Functor,
check: all_funcs,
build: args => entry => {
for (let a of args) if (a(entry)) return true;
for (const a of args) if (a(entry)) return true;
return false;
},
},
Expand All @@ -153,8 +153,8 @@ let operations: Record<string, Operation> = (search.operations = {
type: OperationType.Textual,
check: one_string,
build: ([s]) => {
let deburred = deburr(s);
let deburredW = deburred.some(x => /vy?|w|y/.test(x))
const deburred = deburr(s);
const deburredW = deburred.some(x => /vy?|w|y/.test(x))
? deburred.map(x => x.replace(/vy?|w|y/g, 'ꝡ'))
: undefined;
return entry =>
Expand All @@ -167,7 +167,7 @@ let operations: Record<string, Operation> = (search.operations = {
},
});

for (let trait of RE_TRAITS) {
for (const trait of RE_TRAITS) {
operations[trait] = {
type: OperationType.Other,
check: one_string,
Expand Down Expand Up @@ -203,7 +203,7 @@ function make_re(trait: Trait, s: string): (entry: CachedEntry) => boolean {
.replace(/V\\\+/g, 'V+')
.replace(/V/g, '[aeıiouy]');

let regexp = new RegExp(`^${s}\$`, 'iu');
const regexp = new RegExp(`^${s}\$`, 'iu');
return entry => regexp.test(String(entry.$[trait]));
} catch (_) {
return entry => s === String(entry.$[trait]);
Expand All @@ -224,30 +224,30 @@ function parse_query(
if (!(query instanceof Array)) return 'found non-array branch';
if (!query.length) return 'found empty array node';
query = [...query];
let op_name = query.shift();
let op =
const op_name = query.shift();
const op =
Object.hasOwnProperty.call(operations, op_name) && operations[op_name];
if (!op) return `unknown operation ${op_name}`;
let args;
try {
args = query.map(arg => {
if (typeof arg !== 'object') return arg;
let might_be_it = parse_query(arg);
const might_be_it = parse_query(arg);
if (typeof might_be_it === 'string') throw might_be_it;
return might_be_it;
});
} catch (e) {
return e;
}
let check = op.check(args);
const check = op.check(args);
if (check !== true) return check;
return op.build(args);
}

search.bare_terms = bare_terms;
function bare_terms(o: any[]) {
// `o` must be instanceof Array.
let op = operations[o[0]];
const op = operations[o[0]];
switch (op.type) {
case OperationType.Textual:
return [o[1]];
Expand Down Expand Up @@ -319,9 +319,9 @@ export function search(i: any, uname?: string): string | PresentedEntry[] {
query = parsed.query;
requested_ordering ??= parsed.ordering;
}
let filter = parse_query(query);
const filter = parse_query(query);
if (typeof filter !== 'function') return `malformed query: ${filter}`;
let bares = bare_terms(query),
const bares = bare_terms(query),
deburrs = bares.map(deburr).flat();

const ordering = interpret_ordering(
Expand Down Expand Up @@ -352,6 +352,8 @@ export function search(i: any, uname?: string): string | PresentedEntry[] {
}
}

let presented = results.map(([e, relevance]) => present(e, uname, relevance));
const presented = results.map(([e, relevance]) =>
present(e, uname, relevance),
);
return presented;
}
Loading

0 comments on commit 7f57a0c

Please sign in to comment.