Shrimp accepts custom globals
This commit is contained in:
parent
0e96911879
commit
a535dc9605
|
|
@ -9,16 +9,19 @@ export { globals } from '#prelude'
|
|||
|
||||
export class Shrimp {
|
||||
vm: VM
|
||||
private globals?: Record<string, any>
|
||||
|
||||
constructor() {
|
||||
this.vm = new VM({ instructions: [], constants: [], labels: new Map() }, shrimpGlobals)
|
||||
constructor(globals?: Record<string, any>) {
|
||||
const emptyBytecode = { instructions: [], constants: [], labels: new Map() }
|
||||
this.vm = new VM(emptyBytecode, Object.assign({}, shrimpGlobals, globals ?? {}))
|
||||
this.globals = globals
|
||||
}
|
||||
|
||||
async run(code: string | Bytecode): Promise<any> {
|
||||
let bytecode
|
||||
|
||||
if (typeof code === 'string') {
|
||||
const compiler = new Compiler(code, Object.keys(shrimpGlobals))
|
||||
const compiler = new Compiler(code, Object.keys(Object.assign({}, shrimpGlobals, this.globals ?? {})))
|
||||
bytecode = compiler.bytecode
|
||||
} else {
|
||||
bytecode = code
|
||||
|
|
|
|||
|
|
@ -5,8 +5,12 @@ import { Shrimp } from '..'
|
|||
describe('Shrimp', () => {
|
||||
test('allows running Shrimp code', async () => {
|
||||
const shrimp = new Shrimp()
|
||||
|
||||
expect(await shrimp.run(`1 + 5`)).toEqual(6)
|
||||
expect(await shrimp.run(`type 5`)).toEqual('number')
|
||||
})
|
||||
|
||||
test('maintains state across runs', async () => {
|
||||
const shrimp = new Shrimp()
|
||||
|
||||
await shrimp.run(`abc = true`)
|
||||
expect(shrimp.get('abc')).toEqual(true)
|
||||
|
|
@ -18,4 +22,12 @@ describe('Shrimp', () => {
|
|||
await shrimp.run(`abc = false`)
|
||||
expect(shrimp.get('abc')).toEqual(false)
|
||||
})
|
||||
|
||||
test('allows setting your own globals', async () => {
|
||||
const shrimp = new Shrimp({ hiya: () => 'hey there' })
|
||||
|
||||
await shrimp.run('abc = hiya')
|
||||
expect(shrimp.get('abc')).toEqual('hey there')
|
||||
expect(await shrimp.run('type abc')).toEqual('string')
|
||||
})
|
||||
})
|
||||
Loading…
Reference in New Issue
Block a user