Gathering detailed insights and metrics for @osjwnpm/iure-qui-fugit
Gathering detailed insights and metrics for @osjwnpm/iure-qui-fugit
Gathering detailed insights and metrics for @osjwnpm/iure-qui-fugit
Gathering detailed insights and metrics for @osjwnpm/iure-qui-fugit
npm install @osjwnpm/iure-qui-fugit
Typescript
Module System
Node Version
NPM Version
23
Supply Chain
48.1
Quality
70.7
Maintenance
100
Vulnerability
97.3
License
JavaScript (100%)
Total Downloads
124
Last Day
2
Last Week
5
Last Month
10
Last Year
124
2,206 Commits
1 Watching
1 Branches
1 Contributors
Latest Version
1.0.0
Package Id
@osjwnpm/iure-qui-fugit@1.0.0
Unpacked Size
24.33 kB
Size
8.90 kB
File Count
8
NPM Version
10.5.0
Node Version
20.12.2
Publised On
04 May 2024
Cumulative downloads
Total Downloads
Last day
0%
2
Compared to previous day
Last week
400%
5
Compared to previous week
Last month
900%
10
Compared to previous month
Last year
0%
124
Compared to previous year
36
0-dependency, high-performance, reactive event handling library optimized for both browser and Node.js environments. This library introduces a robust and type-safe abstraction for handling events, reducing boilerplate and increasing code maintainability.
In traditional event handling in TypeScript, events are often represented as strings, and there's no easy way to apply functional transformations like filtering or mapping directly on the event data. This approach lacks type safety, and chaining operations require additional boilerplate, making the code verbose and less maintainable.
The proposed library introduces a robust Event
abstraction that encapsulates event data and provides a suite of functional methods like map
, filter
, reduce
, debounce
, etc., allowing for a more declarative and type-safe approach to event handling. This design facilitates method chaining and composition, making the code more readable and maintainable. For instance, it allows developers to create new events by transforming or filtering existing ones, thus promoting code reusability and modularity.
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
Using pnpm:
1pnpm add @osjwnpm/iure-qui-fugit
Using yarn:
1yarn add @osjwnpm/iure-qui-fugit
Using npm:
1npm install @osjwnpm/iure-qui-fugit
Creates a new event instance.
1import { createEvent, Event } from '@osjwnpm/iure-qui-fugit'; 2 3type ClickEvent = { x: number; y: number; button: number }; 4const clickEvent = createEvent<ClickEvent>(); 5 6type KeyPressEvent = { key: string }; 7const keyPressEvent = createEvent<KeyPressEvent>(); 8 9type ChangeEvent = { target: HTMLInputElement }; 10const changeEvent = createEvent<ChangeEvent>(); 11document.querySelector('input').addEventListener('change', changeEvent);
Returns a new event that will only be triggered once the provided filter function returns true
.
Supports predicate type guard function and filter function as a more concise variant.
1import { Predicate } from '@osjwnpm/iure-qui-fugit'; 2 3type SpacePressEvent = KeyPressEvent & { key: 'Space' }; 4type LeftClickEvent = ClickEvent & { button: 1 }; 5 6const spacePressPredicate: Predicate<KeyPressEvent, SpacePressEvent> = (keyPressEvent): keyPressEvent is SpacePressEvent => keyPressEvent.key === 'Space'; 7// event type is inferred from the predicate function 8const spacePressPredicatedEvent = keyPressEvent.filter(spacePredicate); 9// event type is inferred from the explicitly specified type 10const spacePressFilteredEvent = keyPressEvent.filter<SpacePressEvent>(({ key }) => key === 'Space'); 11 12const leftClickPredicate: Predicate<ClickEvent, LeftClickEvent> = (mouseClickEvent): mouseClickEvent is LeftClickEvent => mouseClickEvent.button === 1; 13// event type is inferred from the predicate function 14const leftClickPredicatedEvent = clickEvent.filter(leftClickPredicate); 15// event type is inferred from the explicitly specified type 16const leftClickFilteredEvent = keyPressEvent.filter<LeftClickEvent>(({ button }) => button === 1);
Returns a new event that maps the values of this event using the provided mapper function.
1const point = { x: 100, y: 100 }; 2const distanceClickEvent = clickEvent.map((click) => (click.x - point.x) ** 2 + (click.y - point.y) ** 2); 3const lowerCaseKeyPressEvent = keyPressEvent.map(({ key }) => key.toLowerCase()); 4const trimmedChangeEvent = changeEvent.map((event) => event.target.value.trim());
Returns a new event that reduces the emitted values using the provided reducer function.
1const sumEvent = numberEvent.reduce((a, b) => a + b, 0); 2sumEvent.on((sum) => console.log(sum)); // 1, 3, 6 3await sumEvent(1); 4await sumEvent(2); 5await sumEvent(3);
Transforms each event's data into multiple events using an expander function. The expander function takes
the original event's data and returns an array of new data elements, each of which will be emitted individually
by the returned Event
instance. This method is useful for scenarios where an event's data can naturally
be expanded into multiple, separate pieces of data which should each trigger further processing independently.
1// Assuming an event that emits a sentence, create a new event that emits each word from the sentence separately. 2const sentenceEvent = new Event<string>(); 3const wordEvent = sentenceEvent.expand(sentence => sentence.split(' ')); 4wordEvent.on(word => console.log('Word:', word)); 5await sentenceEvent('Hello world'); // Logs: "Word: Hello", "Word: world"
Creates a new event that emits values based on a conductor event. The orchestrated event will emit the last value captured from the original event each time the conductor event is triggered. This method is useful for synchronizing events, where the emission of one event controls the timing of another.
1const rightClickPositionEvent = mouseMoveEvent.orchestrate(mouseRightClickEvent); 2 3// An event that emits whenever a "tick" event occurs. 4const tickEvent = new Event<void>(); 5const dataEvent = new Event<string>(); 6const synchronizedEvent = dataEvent.orchestrate(tickEvent); 7synchronizedEvent.on(data => console.log('Data on tick:', data)); 8await dataEvent('Hello'); 9await dataEvent('World!'); 10await tickEvent(); // Logs: "Data on tick: World!"
Creates a debounced event that delays triggering until after a specified interval has elapsed following the last time it was invoked. This method is particularly useful for limiting the rate at which a function is executed. Common use cases include handling rapid user inputs, window resizing, or scroll events.
1const searchEvent = changeEvent.debounce(100); 2searchEvent.value.on(text => searchAPI(text)); // 'text' 3searchEvent.error.on(error => console.error(error)); 4await searchEvent('t'); 5await searchEvent('te'); 6await searchEvent('tex'); 7await searchEvent('text');
Aggregates multiple event emissions into batches and emits the batched events either at specified time intervals or when the batch reaches a predefined size. This method is useful for grouping a high volume of events into manageable chunks, such as logging or processing data in bulk.
1const sendData = changeEvent.batch(100, 5); 2sendData.value.on(data => console.log(data)); // ['data1', 'data2', 'data3', 'data4'] 3sendData.error.on(error => console.error(error)); // 4await sendData('data1'); 5await sendData('data2'); 6await sendData('data3'); 7await sendData('data4');
Transforms an event into an AsyncIterable that yields values as they are emitted by the event. This allows for the consumption of event data using async iteration mechanisms. The iterator generated will yield all emitted values until the event signals it should no longer be active.
1// Assuming an event that emits numbers 2const numberEvent = new Event<number>(); 3const numberIterable = numberEvent.generator(); 4 5await numberEvent(1); 6await numberEvent(2); 7await numberEvent(3); 8 9for await (const num of numberIterable) { 10 console.log('Number:', num); 11}
Creates a queue from the event, where each emitted value is sequentially processed. The returned object allows popping elements from the queue, ensuring that elements are handled one at a time. This method is ideal for scenarios where order and sequential processing are critical.
1// Queueing tasks for sequential execution 2const taskEvent = new Event<string>(); 3const taskQueue = taskEvent.queue(); 4await taskEvent('Task 1'); 5await taskEvent('Task 2'); 6console.log('Processing:', await taskQueue.pop()); // Processing: Task 1 7console.log('Processing:', await taskQueue.pop()); // Processing: Task 2
Merges multiple events into a single event. This function takes any number of Event
instances
and returns a new Event
that triggers whenever any of the input events trigger. The parameters
and results of the merged event are derived from the input events, providing a flexible way to
handle multiple sources of events in a unified manner.
1import { merge } from '@osjwnpm/iure-qui-fugit'; 2 3// Merging mouse and keyboard events into a single event 4const mouseEvent = createEvent<MouseEvent>(); 5const keyboardEvent = createEvent<KeyboardEvent>(); 6const inputEvent = merge(mouseEvent, keyboardEvent); 7inputEvent.on(event => console.log('Input event:', event));
Creates an event that triggers at a specified interval.
1import { createInterval } from '@osjwnpm/iure-qui-fugit'; 2 3const everySecondEvent = createInterval(1000);
1import createEvent, { Event } from '@osjwnpm/iure-qui-fugit'; 2 3// Creates a click event 4type Click = { button: string }; 5const clickEvent = createEvent<Click>(); 6const handleClick = ({ button }: Click) => console.log('Clicked button is', button); 7const unsubscribeClick = clickEvent.on(handleClick); 8 9// Creates a key press event 10type KeyPress = { key: string }; 11const keyPressEvent = createEvent<KeyPress>(); 12const handleKeyPress = ({ key }: KeyPress) => console.log('Key pressed', key); 13const unsubscribeKeyPress = keyPressEvent.on(handleKeyPress); 14 15// Merges click and key press events into input event 16type Input = Click | KeyPress; 17const handleInput = (input: Input) => console.log('Input', input);; 18const inputEvent = Event.merge(clickEvent, keyPressEvent); 19inputEvent.on(handleInput); 20 21// Filters a click event to only include left-click events. 22const handleLeftClick = () => console.log('Left button is clicked'); 23const leftClickEvent = clickEvent.filter(({ button }) => button === 'left'); 24leftClickEvent.on(handleLeftClick); 25 26// Will press Enter after one second 27setTimeout(keyPressEvent, 1000, { key: 'Enter' }); 28// Waits once the first Enter key press event occurs 29await keyPressEvent.first(({ key }) => key === 'Enter').onceAsync(); 30 31keyPressEvent({ key: 'W' }); 32keyPressEvent({ key: 'A' }); 33keyPressEvent({ key: 'S' }); 34keyPressEvent({ key: 'D' }); 35 36clickEvent({ button: 'right' }); 37clickEvent({ button: 'left' }); 38clickEvent({ button: 'middle' }); 39 40// Unsubscribe click listener 41unsubscribeClick(); 42// It does not log anything because of click listener is unsubscribed 43leftClickEvent.off(handleLeftClick); 44 45// Unsubscribe key press listener once first Esc key press occur 46unsubscribeKeyPress.after(() => keyPressEvent 47 .first(({ key }) => key === 'Esc') 48 .onceAsync() 49); 50// Press Esc to unsubscribe key press listener 51keyPressEvent({ key: 'Esc' }); 52 53const messageEvent = createEvent(); 54const messagesBatchEvent = messageEvent.debounce(100); 55 56const messageEvent = createEvent(); 57const messagesBatchEvent = messageEvent.batch(100); 58
A breaking change has been made: events no longer accept a list of arguments. Now, each event accepts a single argument, so simply wrap your arguments in an object. This decision was taken to leverage the benefits of predicate type guards.
License Apache-2.0 Copyright (c) 2021-present Ivan Zakharchanka
No vulnerabilities found.
No security vulnerabilities found.