Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active January 13, 2021 18:02
Show Gist options
  • Save jfet97/8285cbb2aa5920f42f04668030221d28 to your computer and use it in GitHub Desktop.
Save jfet97/8285cbb2aa5920f42f04668030221d28 to your computer and use it in GitHub Desktop.
function createAsyncArray(...values) {
return values.map((v) => ({
resolver: () => {},
promise: Promise.resolve(v),
}));
}
function get(a, i) {
if (a[i] == void 0) {
let resolver = () => {};
const promise = new Promise((res) => {
resolver = res;
});
a[i] = {
promise,
resolver,
};
}
return a[i].promise;
}
function set(a, i, v) {
if (a[i] == void 0) {
a[i] = {
promise: Promise.resolve(v),
resolver: () => {},
};
} else {
a[i].resolver(v);
}
return a[i].promise;
}
// Vengono mappati solo i valori presenti in a, sottoforma di promise,
// durante l'invocazione della funzione map.
// Un'eventuale invocazione di una resolve di un elemento i dell'array risultante
// NON deve influire sull'array di partenza e deve avere un effetto solo se
// la promise i corrente non è già stata risolta.
// La projection potrebbe restituire una promise a sua volta.
function map(a, f) {
return a.map(({ promise }) => {
let new_resolver = () => {};
const new_promise = new Promise((res) => {
new_resolver = res;
promise.then(f).then(res);
});
return {
promise: new_promise,
resolver: new_resolver,
};
});
}
// -----------------------------------------------
/*
const a = createAsyncArray(42, "ciao", {})
get(a, 0).then(x => console.log(x))
get(a, 1).then(x => console.log(x))
get(a, 2).then(x => console.log(x))
get(a, 3).then(x => console.log(x))
const t = setTimeout(() => {
set(a, 3, "gallina")
set(a, 4, 1234)
setTimeout(() => {
get(a, 4).then(x => console.log(x))
}, 1000)
}, 5000)
*/
// -----------------------------------------------
/*
const ma = map(createAsyncArray(1,2,3,4), n => n*2)
get(ma, 0).then(x => console.log(x))
get(ma, 1).then(x => console.log(x))
get(ma, 2).then(x => console.log(x))
get(ma, 3).then(x => console.log(x))
*/
// ----------------------------------------------
/*
const ta = createAsyncArray(1, 2, 3, 4);
const ma2 = map(ta, (n) => new Promise((res) => setTimeout(res, 5000, n * 10)));
get(ma2, 0).then((x) => console.log(x));
get(ma2, 1).then((x) => console.log(x));
get(ma2, 2).then((x) => console.log(x));
get(ma2, 3).then((x) => console.log(x));
const t = setTimeout(() => {
set(ma2, 1, 'uno');
set(ma2, 2, 'due');
setTimeout(() => {
get(ta, 0).then((x) => console.log(x));
get(ta, 1).then((x) => console.log(x));
get(ta, 2).then((x) => console.log(x));
get(ta, 3).then((x) => console.log(x));
}, 4000);
}, 2500);
*/
// ----------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment