Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/GoogleFeud/ts-zero-cost-iters
A typescript plugin which transpiles multiple array methods like map, filter, reduce, etc. into a single for loop.
https://github.com/GoogleFeud/ts-zero-cost-iters
optimization performance plugin typescript
Last synced: about 2 months ago
JSON representation
A typescript plugin which transpiles multiple array methods like map, filter, reduce, etc. into a single for loop.
- Host: GitHub
- URL: https://github.com/GoogleFeud/ts-zero-cost-iters
- Owner: GoogleFeud
- License: mit
- Created: 2021-07-22T06:06:48.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2021-07-23T07:13:48.000Z (about 3 years ago)
- Last Synced: 2024-07-01T00:21:44.467Z (3 months ago)
- Topics: optimization, performance, plugin, typescript
- Language: TypeScript
- Homepage:
- Size: 36.1 KB
- Stars: 6
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ts-zero-cost-iters
`ts-zero-cost-iters` is a typescript plugin which combines array functions like `filter`, `map` and `reduce` into a single for loop. Example:
```ts
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = array.filter(num => num % 2 === 0).map(num => num * 2).join("+");
```to:
```js
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arrLen_1 = array.length, arrItem_1, i_1 = 0;
var result = "";
for (; i_1 < arrLen_1; i_1++) {
arrItem_1 = array[i_1];
if (!(arrItem_1 % 2 === 0))
continue;
result += arrItem_1 * 2 + (i_1 === arrLen_1 - 1 ? "" : "+");
}
```## Install
You need the `ttypescript` package in order to use this:
```npm i ttypescript```After that put this in your tsconfig.json:
```
"compilerOptions": {
//... other options
"plugins": [
{ "transform": "ts-macros" }
]
}
```And run your code with `ttsc`
## ts-zero-cost-iters in-depth
### .length
If the chain ends with a `.length`, then the generated output will NEVER create a new array, it's just going to count the elements.
```ts
const result = array.filter(num => num % 2 === 0).length;
``````js
var arrLen_1 = array.length, arrItem_1, i_1 = 0;
var result = 0;
for (; i_1 < arrLen_1; i_1++) {
arrItem_1 = array[i_1];
if (!(arrItem_1 % 2 === 0))
continue;
result++;
}
```