Skip to content

Instantly share code, notes, and snippets.

@utenma
Created March 30, 2022 21:26
Show Gist options
  • Save utenma/dbef71376141cfad718050e0f0320c26 to your computer and use it in GitHub Desktop.
Save utenma/dbef71376141cfad718050e0f0320c26 to your computer and use it in GitHub Desktop.
/* eslint-disable */
type FilterFunction<In = any, Out = any> = (input: In, next: (flow: boolean, nextInput: Out) => any) => any
export function pipelineSync<FirstIn, FirstOut>(first: FilterFunction<FirstIn, FirstOut>) {
const pipeline: Array<FilterFunction> = [first]
const run = (input: FirstIn): any => pipeline
.reduceRight((nextFunc, currentFunc, index) => {
return (index === 0)
? currentFunc(input, nextFunc)
: (flow: boolean, output: any) => flow
? currentFunc(output, nextFunc)
: undefined
}, (flow: boolean, output: any) => flow ? output : undefined)
type Pipe<CurrOut> = {
pipe: <NextOut>(func: FilterFunction<CurrOut, NextOut>) => Pipe<NextOut>
run: Execute<FirstIn, CurrOut>
}
type Execute<FirstIn, LastOut> = (input: FirstIn) => LastOut
const pipe = <CurrIn, CurrOut>(func: FilterFunction<CurrIn, CurrOut>): Pipe<CurrOut> => {
pipeline.push(func)
return {
pipe,
run
}
}
return pipe(first)
}
const toUpper: FilterFunction<string, string> = (input, next): void =>
next(true, input.toUpperCase())
const replaceSpaces: FilterFunction<string, string> = (input, next): void =>
next(true, input.replace(' ', '-'))
const saluteFromPipes: FilterFunction<string, string> = (input, next): void =>
next(true, input.concat(" from pipes"))
const duplicateString: FilterFunction<string, string> = (input, next): void =>
next(true, input.concat(input))
const getLength: FilterFunction<string, number> = (input, next): void =>
next(true, input.length)
// DEMO execution
const result = pipelineSync(toUpper) // HELLO WORLD
.pipe(replaceSpaces) // HELLO-WORLD
.pipe(saluteFromPipes) // HELLO-WORLD from pipes
.pipe(duplicateString) // HELLO-WORLD from pipesHELLO-WORLD from pipes 
.pipe(getLength) // 44
/* Executes from first and returns last successful chain value */
.run('hello world')
console.log(result) //
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment