getify / monio

The most powerful IO monad implementation in JS, possibly in any language!
http://monio.run
MIT License
1.05k stars 58 forks source link

Is IO example safe? #10

Closed SirMoustache closed 2 years ago

SirMoustache commented 2 years ago

Hey Kyle.

I was reading MONADS.md and when I got to the IO part there is this snippet:

// helpers:
const getProp = prop => obj => obj[prop];
const assignProp = prop => val => obj => obj[prop] = val;

const getElement = id => IO(() => document.getElementById(id));
const getInputValue = id => getElement(id).map( getProp("value") );
const renderTextValue = id => val => (
    getElement(id).map( assignProp("innerText")(val) )
);

const renderCustomerNameIO = (
    getInputValue("customer-name-input")
    .chain( renderTextValue("customer-name-display") )
);

// later:
renderCustomerNameIO.run();

But what will happen if document.getElementById will return null? Also if I try to use TS then I will get a compiler error Object is possibly 'null'. Maybe it will be a good idea to mix this example with Maybe?

// helpers:
const getProp = prop => obj => obj[prop];
const assignProp = prop => val => obj => obj[prop] = val;

const getMaybeProp = prop => maybe => maybe.map(getProp(prop));
const assignMaybeProp = prop => val => maybe => maybe.map(assignProp(prop) (val));
const getElementSafe = id => Maybe.from(document.getElementById(id));

const getElement = id => IO(() => getElementSafe(id));
const getInputValue = id => getElement(id).map( getMaybeProp ("value") );
const renderTextValue = id => val => (
    getElement(id).map( assignMaybeProp ("innerText")(val) )
);

const renderCustomerNameIO = (
    getInputValue("customer-name-input")
    .chain( renderTextValue("customer-name-display") )
);

// later:
renderCustomerNameIO.run();