Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@BenBestmann
BenBestmann / rxjs-suspend.ts
Last active April 1, 2024 20:54
React Suspend behavior for RXJS Observables. Handles the suspension of emitted values of the source observable by prepending values for loading and error states.
function suspend<T>(): OperatorFunction<T, SuspendedValue<T>> {
return (source: Observable<T>) =>
source.pipe(
map((next) => ({
value: next,
isLoading: false,
error: null
})),
catchError((error) => of({ error, isLoading: false, value: null })),
startWith({ isLoading: true, value: null, error: null })
@BenBestmann
BenBestmann / constructor.js
Last active August 23, 2016 06:55
ES6 Constructor Pattern
class Car {
constructor(opts) {
this.model = opts.model;
this.year = opts.year;
this.miles = opts.miles;
}
toString() {
return this.model + ' has driven ' + this.miles + ' miles';
}
}
@BenBestmann
BenBestmann / named-parameters.js
Last active July 1, 2016 14:21
Simulate named parameters in ES5 using an object literal, passing multiple parameters as a single actual parameter.
function selectEntries(options) {
options = options || {};
var start = options.start || 0;
var end = options.end || -1;
var step = options.step || 1;
// function implementation
}
selectEntries({ start: 3, end: 20, step: 2 });
@BenBestmann
BenBestmann / probability.js
Last active July 1, 2016 14:22
Let some event happen by a given probability. Will return true or false given a certain probability in percent (1-99).
function takeChance(probability) {
probability = probability / 100;
return !!probability && Math.random() <= probability;
}