Skip to content

Instantly share code, notes, and snippets.

@VonHeikemen
Created March 29, 2020 21:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save VonHeikemen/0e6d4950bfe91229ee06eee2e3c74515 to your computer and use it in GitHub Desktop.
Save VonHeikemen/0e6d4950bfe91229ee06eee2e3c74515 to your computer and use it in GitHub Desktop.
functional programming stuff... in js.
ENV=development
HOST=http://localhost:5000
const fs = require('fs');
function pipe(...fns) {
return function _piped(...args) {
let current_value = fns[0](...args);
for (let i = 1; i < fns.length; i++) {
current_value = fns[i](current_value);
}
return current_value;
};
}
const Result = {};
Result.Ok = function(value) {
return {
map: fn => Result.Ok(fn(value)),
catchMap: () => Result.Ok(value),
flatMap: fn => fn(value),
cata: (error, success) => success(value),
};
}
Result.Err = function(value) {
return {
map: () => Result.Err(value),
catchMap: fn => Result.Err(fn(value)),
flatMap: () => Result.Err(value),
cata: (error, success) => error(value),
};
}
Result.make_safe = function(fn) {
return function(...args) {
try {
return Result.Ok(fn(...args));
} catch(e) {
return Result.Err(e);
}
}
}
const Maybe = function(value) {
if(value == null) {
return Maybe.Nothing();
}
return Maybe.Just(value);
}
Maybe.Just = function(value) {
return {
map: fn => Maybe.Just(fn(value)),
catchMap: () => Maybe.Just(value),
flatMap: fn => fn(value),
cata: (nothing, just) => just(value),
};
}
Maybe.Nothing = function() {
return {
map: () => Maybe.Nothing(),
catchMap: fn => fn(),
flatMap: () => Maybe.Nothing(),
cata: (nothing, just) => nothing(),
};
}
Maybe.wrap_fun = function(fn) {
return function(...args) {
return Maybe(fn(...args));
}
}
function cat(filepath) {
return fs.readFileSync(filepath, 'utf-8');
}
function grep(pattern) {
return function(content) {
const exp = new RegExp(pattern);
const lines = content.split('\n');
return lines.find(line => exp.test(line));
}
}
function cut({ delimiter, fields }) {
return function(str) {
return str.split(delimiter)[fields - 1];
}
}
const chain = fn => m => m.flatMap(fn);
const unwrap_or = fallback => fm =>
fm.cata(() => fallback, value => value);
const safer_cat = Result.make_safe(cat);
const maybe_host = Maybe.wrap_fun(grep('^HOST='));
const get_value = Maybe.wrap_fun(cut({delimiter: '=', fields: 2}));
const get_host = pipe(
safer_cat,
chain(maybe_host),
chain(get_value),
unwrap_or('http://127.0.0.1:3000')
);
console.log( get_host('.env') );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment