Compare commits

...

8 Commits
0.3.0 ... 0.8.0

Author SHA1 Message Date
2fe8cdb96a Added upload function which tracks progress
All checks were successful
Build / Build NPM Project (push) Successful in 16s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
2024-04-24 06:57:15 -04:00
34c2df7a1a Fixed import
All checks were successful
Build / Build NPM Project (push) Successful in 16s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
2024-04-23 09:09:07 -04:00
1d5509a078 Fixed export
All checks were successful
Build / Build NPM Project (push) Successful in 16s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
2024-04-23 09:03:51 -04:00
9f57b93a9f Download stream
All checks were successful
Build / Build NPM Project (push) Successful in 17s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 10s
2024-04-23 09:02:10 -04:00
d0e9cbcaa6 Added download utilities
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 7s
Build / Publish (push) Successful in 14s
2024-04-21 21:33:38 -04:00
67b314b507 Added download function using fetch and links
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 7s
Build / Publish (push) Successful in 16s
2024-04-21 21:03:07 -04:00
f5d66f0d8f Fixed aset export
All checks were successful
Build / Build NPM Project (push) Successful in 35s
Build / Tag Version (push) Successful in 7s
Build / Publish (push) Successful in 13s
2024-04-16 14:16:30 -04:00
18c4366866 Added ASet
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 8s
Build / Publish (push) Successful in 15s
2024-04-16 14:05:41 -04:00
7 changed files with 151 additions and 5 deletions

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "@ztimson/utils",
"version": "0.3.0",
"version": "0.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ztimson/utils",
"version": "0.3.0",
"version": "0.4.0",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.12",

View File

@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.3.0",
"version": "0.8.0",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

58
src/aset.ts Normal file
View File

@ -0,0 +1,58 @@
export class ASet<T> extends Array {
get size() {
return this.length;
}
constructor(elements: T[] = []) {
super();
if(!!elements?.['forEach'])
elements.forEach(el => this.add(el));
}
add(el: T) {
if(!this.has(el)) this.push(el);
}
delete(el: T) {
const index = this.indexOf(el);
if(index != -1) this.slice(index, 1);
}
difference(set: ASet<T>) {
return new ASet<T>(this.reduce((acc, el) => {
if(!set.has(el)) acc.push(el);
return acc;
}, []));
}
has(el: T) {
return this.indexOf(el) != -1;
}
intersection(set: ASet<T>) {
return new ASet<T>(this.reduce((acc, el) => {
if(set.has(el)) acc.push(el);
return acc;
}, []));
}
isDisjointFrom(set: ASet<T>) {
return this.intersection(set).size == 0;
}
isSubsetOf(set: ASet<T>) {
return this.findIndex(el => !set.has(el)) == -1;
}
isSuperset(set: ASet<T>) {
return set.findIndex(el => !this.has(el)) == -1;
}
symmetricDifference(set: ASet<T>) {
return new ASet([...this.difference(set), ...set.difference(this)]);
}
union(set: ASet<T> | Array<T>) {
return new ASet([...this, ...set]);
}
}

53
src/download.ts Normal file
View File

@ -0,0 +1,53 @@
import {TypedEmitter, TypedEvents} from './emitter';
export type DownloadEvents = TypedEvents & {
complete: (blob: Blob) => any;
failed: (error: Error) => any;
progress: (progress: number) => any;
}
export function download(href: any, name: string) {
const a = document.createElement('a');
a.href = href;
a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
/**
* Download a URL using fetch so progress can be tracked. Uses Typed Emitter to emit a "progress" &
* "complete" event.
*
* @param {string} url
* @param {string} downloadName
* @return {TypedEmitter<DownloadEvents>}
*/
export function downloadProgress(url: string, downloadName?: string) {
const progress = new TypedEmitter<DownloadEvents>();
fetch(url).then(response => {
if(!response.ok) return progress.emit('failed', new Error(response.statusText));
const contentLength = response.headers.get('Content-Length') || '0';
const total = parseInt(contentLength, 10);
let chunks: any[] = [], loaded = 0;
const reader = response.body?.getReader();
reader?.read().then(function processResult(result) {
if(result.done) {
const blob = new Blob(chunks);
if(downloadName) {
const url = URL.createObjectURL(blob);
download(url, downloadName);
URL.revokeObjectURL(url);
}
progress.emit('complete', blob);
} else {
const chunk = result.value;
chunks.push(chunk);
loaded += chunk.length;
progress.emit('progress', loaded / total);
reader.read().then(processResult);
}
});
}).catch(err => progress.emit('failed', err));
return progress;
}

View File

@ -1,4 +1,6 @@
export * from './array';
export * from './aset';
export * from './download';
export * from './emitter';
export * from './errors';
export * from './logger';
@ -6,4 +8,5 @@ export * from './misc';
export * from './objects';
export * from './string';
export * from './time';
export * from './upload';
export * from './xhr';

30
src/upload.ts Normal file
View File

@ -0,0 +1,30 @@
import {TypedEmitter, TypedEvents} from './emitter';
export type UploadEvents = TypedEvents & {
complete: () => any;
failed: (err: Error) => any;
progress: (progress: number) => any;
}
function uploadProgress(files : File | FileList, url: string) {
const xhr = new XMLHttpRequest();
const progress = new TypedEmitter<UploadEvents>();
const formData = new FormData();
(Array.isArray(files) ? files : [files])
.forEach(f => formData.append('file', f));
xhr.upload.addEventListener("progress", (event) => {
if(event.lengthComputable) progress.emit('progress', event.loaded / event.total);
});
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) progress.emit('complete');
else progress.emit('failed', new Error(xhr.responseText));
}
};
xhr.open("POST", url, true);
xhr.send(formData);
return progress;
}

View File

@ -1,3 +1,4 @@
import {TypedEmitter, TypedEvents} from './emitter.ts';
import {clean} from './objects';
export type Interceptor = (request: Response, next: () => void) => void;
@ -7,6 +8,7 @@ export type RequestOptions = {
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
body?: any;
headers?: {[key: string | symbol]: string | null | undefined};
skipConverting?: boolean;
[key: string]: any;
}
@ -67,8 +69,8 @@ export class XHR {
}
if(!resp.ok) throw new Error(resp.statusText);
if(resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json();
if(resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text();
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json();
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text();
return resp;
});
}