Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Last active January 5, 2019 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbreckmckye/b9f0f54d1621116d415cbb0f9947364b to your computer and use it in GitHub Desktop.
Save jbreckmckye/b9f0f54d1621116d415cbb0f9947364b to your computer and use it in GitHub Desktop.
// Get a WebGL context
import {Perhaps, None, Some, Any} from 'highly-questionable';
const canvas = document.createElement('canvas');
const context = Perhaps
.of(canvas.getContext('webgl2'))
.or(canvas.getContext('webgl'))
.orFrom(()=> canvas.getContext('experimental-webgl'));
context.case(
Some, ctx => console.log('We have a context'),
None, ()=> throw new Error('No context available')
);
context.catch(
Any, err => console.error(`Failed: ${err.message}`)
);
// Promise interop
import {Perhaps, Rejection} from 'highly-questionable';
const fetchUsers = async ()=> {...};
const userEmail = Perhaps
.from(fetchUsers)
.flatMap(
user => Perhaps
.of(user.email)
.or(user.email_address)
.or(Perhaps
.of(user.metadata)
.map(meta => meta.email || meta.email_address)
)
.map(m => 'mailto:' + m)
);
// jQuery esque dom querying
import {Perhaps} from 'highly-questionable';
function queryAll(el: HTMLElement, selector: string) {
return Perhaps
.of(el.querySelectorAll(selector))
.map(results => Array.from(results));
}
const link = Perhaps
.of(queryAll(document, 'div'))
.flatMap(div => queryAll(div, 'li'))
.flatMap(li => queryAll(li, 'a'));
// case matching
import {Perhaps, Some, None, Type, Same} from 'highly-questionable';
const isEmail = /^.+@.+$/g;
const userName = Perhaps
.of(window.prompt('What is your name?'));
const result = userName.case(
isEmail, x => 'mailto:' + x,
Type(Error), e => 'error:' + e.message,
Some, Same
None, 'unnamed'
);
import {Perhaps, Some, None, Same} from 'highly-questionable';
const isEmail = /^.+@.+$/g;
const lengthInvalid = (str: String) => str.length > 255;
const email = Perhaps
.of(window.prompt('What is your email?'))
.case(
None, () => throw new Error('No email provided'),
lengthInvalid, ()=> throw new Error('Length is too long')
isEmail, Same
)
.map(email => sendWelcomeEmail(email);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment