Skip to content

Commit 602c1b9

Browse files
feat(lispy): add string/regex builtins
1 parent 9d95852 commit 602c1b9

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

packages/lispy/src/index.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { selectKeysObj } from "@thi.ng/object-utils/select-keys";
1515
import type { ASTNode, Expression, Implementations, Sym } from "@thi.ng/sexpr";
1616
import { parse } from "@thi.ng/sexpr/parse";
1717
import { runtime } from "@thi.ng/sexpr/runtime";
18+
import { capitalize, lower, upper } from "@thi.ng/strings/case";
1819
import { KERNEL } from "./kernel.js";
1920

2021
export type Env = Record<string, any>;
@@ -221,6 +222,23 @@ export const ENV: Env = {
221222
// there're no further items
222223
next: (arg: any) => (arg.length > 1 ? arg.slice(1) : undefined),
223224

225+
// strings
226+
lower,
227+
upper,
228+
capitalize,
229+
"pad-left": (x: string, width: number, fill: string) =>
230+
x.padStart(width, fill),
231+
"pad-right": (x: string, width: number, fill: string) =>
232+
x.padEnd(width, fill),
233+
substr: (x: string, from: number, to?: number) => x.substring(from, to),
234+
trim: (x: string) => x.trimEnd(),
235+
regexp: (src: string, flags?: string) => new RegExp(src, flags),
236+
"re-test": (regexp: RegExp, x: string) => regexp.test(x),
237+
"re-match": (regexp: RegExp, x: string) => regexp.exec(x),
238+
replace: (x: string, regexp: RegExp, replacement: string) =>
239+
x.replace(regexp, replacement),
240+
241+
// misc
224242
print: console.log,
225243

226244
env: () =>
@@ -232,13 +250,13 @@ export const ENV: Env = {
232250
};
233251

234252
/**
235-
* Evaluates given S-expression(s) and returns result of last. If no environment
236-
* is provided, uses {@link ENV}.
253+
* Parses & evaluates given S-expression(s) and returns result of last one. If
254+
* no environment is provided, uses {@link ENV}.
237255
*
238256
* @param src
239257
* @param env
240258
*/
241-
export const evalExpressions = (src: string, env: Env = ENV) =>
259+
export const evalSource = (src: string, env: Env = ENV) =>
242260
parse(src).children.reduce((_, x) => interpret(x, env), <any>undefined);
243261

244262
export const evalArgs = (nodes: ASTNode[], env: Env = ENV) =>
@@ -252,4 +270,4 @@ export const interpret = runtime<Implementations<Env, any>, Env, any>({
252270
});
253271

254272
// evaluate built-ins and inject into root env
255-
evalExpressions(KERNEL);
273+
evalSource(KERNEL);

0 commit comments

Comments
 (0)