Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created March 6, 2017 12:39
Show Gist options
  • Select an option

  • Save MikeMKH/2bed5b91ca884e3dfcd92ecf94be854a to your computer and use it in GitHub Desktop.

Select an option

Save MikeMKH/2bed5b91ca884e3dfcd92ecf94be854a to your computer and use it in GitHub Desktop.
Basic Maybe examples using folktale with mocha and expect.js
const Maybe = require('data.maybe');
const Nothing = Maybe.Nothing;
const Just = Maybe.Just;
const expect = require('expect.js');
describe('truth', () => {
it('will be true', () => {
expect(true).to.equal(true);
})
});
// examples from http://robotlolita.me/2013/12/08/a-monad-in-practicality-first-class-failures.html#maybe-things-dont-work
describe('Maybe', () => {
describe('example uses', ()=> {
describe('first', () => {
const first = xs => xs && xs.length > 0 ? Just(xs[0]) : Nothing();
const concatenate = (ma, mb) =>
ma.chain(a => mb.chain(b => mb.of(a + b)));
it('given a collection it must return just the first value', () => {
const actual = first('abc');
expect(actual).to.eql(Just('a'));
expect(actual.isJust).to.be.ok();
}),
it('given an empty collection it must return nothing', () => {
const actual = first([]);
expect(actual).to.eql(Nothing());
expect(actual.isNothing).to.be.ok();
}),
it('given a null it must return nothing', () => {
const actual = first(null);
expect(actual.isNothing).to.be.ok();
}),
it('given just two values it must concatenate values', () => {
var actual = concatenate(Just(1), Just(2));
expect(actual).to.eql(Just(1 + 2));
actual = concatenate(Just('Hello '), Just('Mike'));
expect(actual).to.eql(Just('Hello Mike'));
}),
it('given nothing and just a value it must concatenate to nothing', () => {
var actual = concatenate(Just(42), Nothing());
expect(actual).to.eql(Nothing());
actual = concatenate(Nothing(), Just(42));
expect(actual).to.eql(Nothing());
}),
it('given nothing and nothing it must concatenate to nothing', () => {
const actual = concatenate(Nothing(), Nothing());
expect(actual.isNothing).to.be.ok();
}),
it('given arrays of value it must be able to concatenate them', () => {
const consonants = 'bcd';
const vowels = 'aei';
const nothing = []
const firstConsonant = first(consonants);
const firstVowel = first(vowels);
const firstNothing = first(nothing);
expect(concatenate(firstVowel, firstNothing)).to.eql(Nothing());
expect(concatenate(firstVowel, firstConsonant)).to.eql(Just('ab'));
});
});
});
});
@MikeMKH

MikeMKH commented Mar 6, 2017

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment