https://github.com/denorid/genfn
A module that helps you to write generated functions
https://github.com/denorid/genfn
deno function-compiler function-generator javascript typescript
Last synced: about 1 month ago
JSON representation
A module that helps you to write generated functions
- Host: GitHub
- URL: https://github.com/denorid/genfn
- Owner: denorid
- License: mit
- Created: 2022-02-27T20:27:24.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-02-27T21:24:01.000Z (over 4 years ago)
- Last Synced: 2025-12-12T22:52:35.980Z (6 months ago)
- Topics: deno, function-compiler, function-generator, javascript, typescript
- Language: TypeScript
- Homepage:
- Size: 17.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @denorid/genfn
A module that helps you to write generated functions in [Deno](https://deno.land),
based on npm [generate-function](https://github.com/mafintosh/generate-function) package.
## Usage
```TypeScript
import { genFn } from "https://deno.land/x/denorid_genfn@1.0.0/mod.ts"
const addNumber = (val: number) => {
const gen = genFn(`
function add(n) {
return n + ${val}
}
`);
return gen.toFunction();
}
const addTen = addNumber(10);
console.log(addTen.toString()); // prints the generated function
console.log("5 + 10 =", addTen(5));
```
If you need to close over variables in your generated function pass them to `toFunction(scope?: Record)`
```TypeScript
function multiply(a: number, b: number) {
return a * b;
}
function addAndMultiplyNumber(val: number) {
const gen = genFn(`
function (n) {
if (typeof n !== 'number') {
throw new Error('argument should be a number')
}
const result = multiply(${val}, n + ${val})
return result
}
`);
return gen.toFunction({ multiply });
}
const addAndMultiply2 = addAndMultiplyNumber(2);
console.log(addAndMultiply2.toString()); // prints the generated function
console.log("(3 + 2) * 2 =", addAndMultiply2(3));
```
You can call `gen.generate(code: string | string[])` as many times as you want to append more source code to the function.