Skip to content

Instantly share code, notes, and snippets.

@Wikiko
Created September 14, 2018 12:10
Show Gist options
  • Save Wikiko/0600acfa60c7be86bfa5386c847be38f to your computer and use it in GitHub Desktop.
Save Wikiko/0600acfa60c7be86bfa5386c847be38f to your computer and use it in GitHub Desktop.
class Future {
slots = [];
completed = false;
value;
ready(slot) {
if (this.completed) {
slot(this.value);
} else {
this.slots.push(slot);
}
}
complete(val) {
// ensure immutability
if (this.completed) {
throw "Can't complete an already completed future!";
}
this.value = val;
this.completed = true;
// notify subscribers
this.slots.forEach(slot => slot(val));
this.slots = null;
}
fmap(fn) {
const fut = new Future();
this.ready(function (val) {
fut.complete(fn(val));
});
return fut;
}
static unit(val) {
const fut = new Future();
fut.complete(val);
return fut;
}
static delay(v, millis) {
const fut = new Future();
fut.complete(val);
return fut;
}
}
// example with readFile ...
const fs = require(fs);
function readFileF(file, options) {
const f = new Future();
fs.readFile(file, options, function (err, data) {
if (err) throw err;
f.complete(data);
return f;
});
}
logF(readFileF('test.txt', { encoding: 'utf8' }));
// a simple log utility
function logF(f) {
f.ready(v => console.log(v));
}
logF(Future.unit('hi now'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment