monet / monet.js

monet.js - Monadic types library for JavaScript
https://monet.github.io/monet.js/
MIT License
1.6k stars 114 forks source link

Maybe.fromEmpty? #213

Closed customcommander closed 5 years ago

customcommander commented 5 years ago

I was wondering if it would make sense to have this new static method?

Maybe.fromEmpty([]);
//=> None
Maybe.fromEmpty({});
//=> None
Maybe.fromEmpty('');
//=> None
Maybe.fromEmpty(null);
//=> None
Maybe.fromEmpty(undefined);
//=> None

It could (or perhaps should) delegate to fantasy-land/empty to work out if a given value is its type's empty value.

Use case:

I have a css rules object which contains css rules to apply to a string if there's any. Otherwise the string is returned as is. Problem is that the object may actually be "empty" i.e. it is an object but has no properties.

const styles = (css, text) =>
  Maybe
    .fromEmpty(css) // e.g. {'text-decoration': 'underline', 'color': 'red'}
    .map(obj => obj.entries()) // [['text-decoration', 'underline'], ['color', 'red']]
    .map(arr => arr.map(pair => pair.join(':'))) // ['text-decoration:underline', 'color:red']
    .map(arr => arr.join(';')) // 'text-decoration:underline;color:red'
    .fold(text)(str => `<span style="${str}">${text}</span>`);

styles({'font-style': 'italic'}, 'foo');
//=> '<span style="font-style:italic">foo</span>'

styles({}, 'foo');
//=> 'foo'

Any thoughts?

ulfryk commented 5 years ago

👍 great idea @customcommander I had one usecase just today :)

Can you implement it?

customcommander commented 5 years ago

I would love it. I'll give it a shot :)

ulfryk commented 5 years ago

snapshot released as monet@0.9.0-422