Skip to content

Commit

Permalink
fix: completed example
Browse files Browse the repository at this point in the history
  • Loading branch information
ilteoood committed Dec 8, 2023
1 parent e89b934 commit 169e9e6
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 106 deletions.
42 changes: 22 additions & 20 deletions examples/fastify/src/index.mjs
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import { faker } from '@faker-js/faker';
import fastify from 'fastify';
import { Readable } from 'node:stream';
import { faker } from "@faker-js/faker";
import fastify from "fastify";
import { Readable } from "node:stream";

const server = fastify();

const itemsToGenerate = 1_000_000;
const itemsToGenerate = 100_000;

server.get('/users', (request, reply) => {
return reply
.header('Content-Type', 'application/octet-stream')
.send(
Readable.from(function* () {
for (let i = 0; i < itemsToGenerate; i++) {
yield JSON.stringify({
name: faker.person.firstName(),
surname: faker.person.lastName(),
age: faker.number.int({ min: 0, max: 100 }),
}).concat(i === itemsToGenerate ? '' : '\n');
}
}())
);
server.get("/users", (_, reply) => {
const readableStream = Readable.from(
(function* () {
for (let i = 1; i <= itemsToGenerate; i++) {
yield JSON.stringify({
name: faker.person.firstName(),
surname: faker.person.lastName(),
age: faker.number.int({ min: 0, max: 100 }),
}).concat(i === itemsToGenerate ? "" : "\n");
}
})(),
);

return reply
.header("Content-Type", "application/octet-stream")
.send(readableStream);
});

await server.listen({ port: 3000 }, (error, address) => {
server.log.info(`server listening on ${address}`);
})
server.log.info(`server listening on ${address}`);
});
4 changes: 3 additions & 1 deletion examples/vanilla-ts/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
</head>
<body>
<div style="display:flex; flex-direction: column;">
<ul id="adultList"></ul>
<ul id="adultList">
Calculating...
</ul>
<ul id="childList"></ul>
</div>
<div id="app"></div>
Expand Down
61 changes: 17 additions & 44 deletions examples/vanilla-ts/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,23 @@
import PersonWorker from './worker?worker'
import PersonWorker from "./worker?worker";

type PersonKind = 'adult' | 'child'
type PersonKind = "adult" | "child";

interface WorkerMessage {
kind: PersonKind
textContent: string
kind: PersonKind;
mean: number;
}

const containers = {
adult: document.querySelector<HTMLUListElement>('#adultList') as HTMLUListElement,
child: document.querySelector<HTMLUListElement>('#childList') as HTMLUListElement
}

const people: Record<PersonKind, string[]> = {
adult: [],
child: []
}

const worker = new PersonWorker()


worker.onmessage = ({ data: { kind, textContent } }: MessageEvent<WorkerMessage>) => {
people[kind].push(textContent)
}

const appendElement = (kind: PersonKind) => {
if (people[kind].length > 0) {
const fragment = document.createDocumentFragment()

for (const person of people[kind]) {
const li = document.createElement('li')
li.textContent = person
fragment.append(li)
}

people[kind] = []
containers[kind].append(fragment)
}
}

const resursiveAnimationFrame = () => {
window.requestAnimationFrame(() => {
appendElement('adult')
appendElement('child')
resursiveAnimationFrame()
})
}

setTimeout(resursiveAnimationFrame, 1000)
adult: document.querySelector<HTMLUListElement>(
"#adultList",
) as HTMLUListElement,
child: document.querySelector<HTMLUListElement>(
"#childList",
) as HTMLUListElement,
};

const worker = new PersonWorker();

worker.onmessage = ({ data: { kind, mean } }: MessageEvent<WorkerMessage>) => {
containers[kind].textContent = `The mean age for ${kind} is ${mean}`;
};
73 changes: 44 additions & 29 deletions examples/vanilla-ts/src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,52 @@
import { fetchText } from '@ilteoood/re-flusso/fetchText'
import { filter } from '@ilteoood/re-flusso/filter'
import { map } from '@ilteoood/re-flusso/map'
import { parser } from '@ilteoood/re-flusso/ndJson/parser'
import { pipeline } from '@ilteoood/re-flusso/pipeline'
import { fetchText } from "@ilteoood/re-flusso/fetchText";
import { filter } from "@ilteoood/re-flusso/filter";
import { map } from "@ilteoood/re-flusso/map";
import { parse } from "@ilteoood/re-flusso/ndJson/parse";
import { pipeline } from "@ilteoood/re-flusso/pipeline";
import { reduce } from "@ilteoood/re-flusso/reduce";

interface User {
name: string
surname: string
age: number
name: string;
surname: string;
age: number;
}

const response = await fetch('/users')
const [response1, response2] = fetchText(response).tee()
interface ReducedUser {
people: number;
ages: number;
}

const userMapper = (user: User) => `${user.name} ${user.surname} - ${user.age}`
const response = await fetch("/users");
const [response1, response2] = fetchText(response).tee();

const sendMessage = (kind: 'adult' | 'child') => (textContent: string) => {
self.postMessage({ kind, textContent })
}
const calculateMean = (reducedUser: ReducedUser) =>
reducedUser.ages / reducedUser.people || 0;

const ageReducer = (acc: ReducedUser, user: User) => {
acc.people++;
acc.ages += user.age;
return acc;
};

const sendMessage = (kind: "adult" | "child") => (mean: number) => {
self.postMessage({ kind, mean });
};

await Promise.all([
pipeline(
response1,
parser(),
filter(user => user.age >= 18),
map(userMapper),
new WritableStream({ write: sendMessage('adult') })
),
pipeline(
response2,
parser(),
filter(user => user.age < 18),
map(userMapper),
new WritableStream({ write: sendMessage('child') })
)
])
pipeline(
response1,
parse(),
filter((user) => user.age >= 18),
reduce(ageReducer, { people: 0, ages: 0 }),
map(calculateMean),
new WritableStream({ write: sendMessage("adult") }),
),
pipeline(
response2,
parse(),
filter((user) => user.age < 18),
reduce(ageReducer, { people: 0, ages: 0 }),
map(calculateMean),
new WritableStream({ write: sendMessage("child") }),
),
]);
16 changes: 8 additions & 8 deletions examples/vanilla-ts/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { defineConfig } from 'vite';
import { defineConfig } from "vite";

export default defineConfig({
server: {
proxy: {
'/users': {
target: 'http://localhost:3000'
},
},
},
server: {
proxy: {
"/users": {
target: "http://localhost:3000",
},
},
},
});
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@
"dist"
],
"scripts": {
"format": "biome format ./src ./test",
"format": "biome format ./src ./test ./examples",
"format:fix": "pnpm run format --write",
"sort": "biome check --apply-unsafe ./src ./test",
"lint": "biome lint ./src ./test",
"lint:fix": "biome check --apply ./src ./test",
"sort": "biome check --apply-unsafe ./src ./test ./examples",
"lint": "biome lint ./src ./test ./examples",
"lint:fix": "biome check --apply ./src ./test ./examples",
"test": "pnpm run \"/^test:.*/\"",
"test:node": "vitest",
"test:browser": "vitest --config ./vitest-browser.config.ts",
Expand Down

0 comments on commit 169e9e6

Please sign in to comment.