@voiceflow/common
Version:
Junk drawer of utility functions
49 lines (48 loc) • 1.56 kB
JavaScript
export const isFunction = (value) => typeof value === 'function';
export const compose = (...transforms) => (value) => {
if (transforms.length === 1) {
return transforms[0](value);
}
if (transforms.length === 2) {
return transforms[0](transforms[1](value));
}
return transforms.reduceRight((acc, transform) => transform(acc), value);
};
export const noop = () => undefined;
export const identity = (value) => value;
export const stringify = (value) => (typeof value === 'string' ? value : String(value));
export const chain = (...fns) => (...args) => {
// perf optimization, most of the time we have one or two functions
if (fns.length === 1) {
fns[0]?.(...args);
}
else if (fns.length === 2) {
fns[0]?.(...args);
fns[1]?.(...args);
}
else {
fns.forEach((fn) => fn?.(...args));
}
};
export const chainVoid = (...fns) => () => chain(...fns)();
export const chainAsync = (...fns) => async (...args) => {
// perf optimization, most of the time we have one or two functions
if (fns.length === 1) {
await fns[0]?.(...args);
}
else if (fns.length === 2) {
await fns[0]?.(...args);
await fns[1]?.(...args);
}
else {
for (const fn of fns) {
// eslint-disable-next-line no-await-in-loop
await fn?.(...args);
}
}
};
export const chainVoidAsync = (...fns) => () => chainAsync(...fns)();
export const withEffect = (callback) => (value) => {
callback(value);
return value;
};