Skip to content

Instantly share code, notes, and snippets.

View basarat's full-sized avatar
🌹
youtube.com/basaratali

Basarat Ali Syed basarat

🌹
youtube.com/basaratali
View GitHub Profile
/**
* Adds retries to an async function.
*/
async function retry<T>(fn: () => Promise<T>, n: number): Promise<T> {
let lastError: any;
for (let index = 0; index < n; index++) {
try {
return await fn();
}
catch (e) {
/** If true is returned it is used to prevent a nav away */
export type Check = () => true | false | undefined;
/** Checks we need to do before leave */
let checks: Check[] = [];
/** Only alert in browsers */
if (typeof window !== 'undefined') {
const getMessageIfAny = () => {
let message: ReturnType<Check> = false;
import { Validator } from 'formstate';
export const email: Validator<string | null | undefined> = (value: string | null | undefined) => {
if (value == null || value == '') return null;
value = value.trim();
// src : http://emailregex.com/
if (!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g.exec(value)) {
return "Not a valid email address";
}
return null;
}
@basarat
basarat / pre.tsx
Last active August 22, 2018 00:49
Debug JavaScript objects in TypeScript React
export const Pre: React.SFC<{ children: any }> = (props) => {
return <pre>{JSON.stringify(props.children, null, 2)}</pre>
}
@basarat
basarat / md5.ts
Created November 2, 2017 00:43
Create md5 using TypeScript / JavaScript / NodeJS
import * as crypto from 'crypto';
export const md5 = (contents: string) => crypto.createHash('md5').update(contents).digest("hex");
import { observer } from 'mobx-react';
import * as field from './field';
import * as React from 'react';
import { InputStyles } from '../base/inputs';
import { classes, cssRaw } from 'typestyle';
import { FocusClassNames } from '../utils/dom';
import { Dates } from '../utils/validation';
import { Colors } from '../base/styles';
/**
@basarat
basarat / app.tsx
Last active February 20, 2017 00:21
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { App } from './app';
ReactDOM.render(<App/>, document.getElementById('root'))
import {setStatefulModules} from 'fuse-box/modules/fuse-hmr';
setStatefulModules(name => {
export class AppState {
@observable loggedIn = false;
@action setLoggedIn(value: boolean){
this.loggedIn = value;
}
}
// Don't want this executing again
export const appState = new AppState();
let listener = ()=>null
// Don't want to execute this line again
window.addEventListener("hashchange",()=>{
listener();
});
// You can call this as many times as you want
export const onHashChange(_listener){
listener = _listener;
const foo = require('./foo');
console.log(foo.getFoo()); // hello
foo.setFoo('world');
setTimeout(()=>{
const foo = require('./foo'); // You require it again. But you get the same instance!
console.log(foo.getFoo()); // world
});