Skip to content

Commit

Permalink
Make the type definitions more accurate
Browse files Browse the repository at this point in the history
Add `operators.array` to `ParserOptions`

Add types for `Parser.unaryOps`, `Parser.functions`, and `Parser.consts`

Add boolean and array to `Value` type, since `evaluate` can return those.
```ts
Parser.evaluate("true") // returns boolean
Parser.evaluate("[1,2,3]") // returns array
```

Make function `Value`s take `any[]` instead of `Value[]`. TypeScript
won't let you assign a function that only takes `number`/`string` etc.
to `(...args: Value[]) => Value`, so make it take any.
```ts
let x: (...args: Value[]) => Value = Math.max // TypeScript will error
let x: (...args: any[]) => Value = Math.max // TypeScript is happy
```

Update `evaluate`'s and `simplify`'s definition to only take an object
of `Value`s instead of a `Value` (which can also be array/boolean/etc.)

Update `evaluate` functions to return a `Value` type instead of just
`number`
  • Loading branch information
jesse-r-s-hines committed Nov 13, 2021
1 parent 6e889e0 commit 45678bc
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions parser.d.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
export type Value = number
| string
| ((...args: Value[]) => Value)
| boolean
| ValueFunction
| Value[]
| { [propertyName: string]: Value };

export interface Values {
[propertyName: string]: Value;
}

export type ValueFunction = ((...args: any[]) => Value)

export interface ParserOptions {
allowMemberAccess?: boolean;
operators?: {
Expand Down Expand Up @@ -51,6 +55,7 @@ export interface ParserOptions {
max?: boolean,
assignment?: boolean,
fndef?: boolean,
array?: boolean
cbrt?: boolean,
expm1?: boolean,
log1p?: boolean,
Expand All @@ -61,20 +66,20 @@ export interface ParserOptions {

export class Parser {
constructor(options?: ParserOptions);
unaryOps: any;
functions: any;
consts: any;
unaryOps: {[name: string]: ((arg: any) => Value)};
functions: {[name: string]: ValueFunction};
consts: Values;
parse(expression: string): Expression;
evaluate(expression: string, values?: Value): number;
evaluate(expression: string, values?: Values): Value;
static parse(expression: string): Expression;
static evaluate(expression: string, values?: Value): number;
static evaluate(expression: string, values?: Values): Value;
}

export interface Expression {
simplify(values?: Value): Expression;
evaluate(values?: Value): any;
simplify(values?: Values): Expression;
evaluate(values?: Values): Value;
substitute(variable: string, value: Expression | string | number): Expression;
symbols(options?: { withMembers?: boolean }): string[];
variables(options?: { withMembers?: boolean }): string[];
toJSFunction(params: string | string[], values?: Value): (...args: any[]) => number;
toJSFunction(params: string | string[], values?: Values): ValueFunction;
}

0 comments on commit 45678bc

Please sign in to comment.