Created
March 30, 2022 21:28
-
-
Save utenma/f87876a117e55ccd52940399779ca315 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable */ | |
type PipeFlow<Payload, Stage extends string> = { | |
stage: Stage | |
status: boolean | |
payload?: Payload | |
} | |
type FilterFunction<In = any, Out = any, Stage extends string = string> = (input: In) => PipeFlow<Out, Stage> | |
export function pipelineSync<FirstIn, FirstOut>(first: FilterFunction<FirstIn, FirstOut>) { | |
const pipeline: Array<FilterFunction> = [first] | |
const run = (input: FirstIn): any => { | |
let flow: PipeFlow<any, string> | |
flow = pipeline[0](input) | |
for (let index = 1; index < pipeline.length; index++) { | |
if (flow.status) | |
flow = pipeline[index](flow.payload) | |
} | |
return flow | |
} | |
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, 'TO_UPPER'> = (input) => ({ | |
stage: 'TO_UPPER', | |
status: true, | |
payload: input.toUpperCase() | |
}) | |
const replaceSpaces: FilterFunction<string, string, 'REPLACE'> = (input) => ({ | |
stage: 'REPLACE', | |
status: true, | |
payload: input.replace(' ', '-') | |
}) | |
const saluteFromPipes: FilterFunction<string, string, 'SALUTE'> = (input) => ({ | |
stage: 'SALUTE', | |
status: true, | |
payload: input.concat(" from pipes") | |
}) | |
const duplicateString: FilterFunction<string, string, 'DUPLICATE'> = (input) => ({ | |
stage: 'DUPLICATE', | |
status: true, | |
payload: input.concat(input) | |
}) | |
const getLength: FilterFunction<string, number, 'LENGTH'> = (input) => ({ | |
stage: 'LENGTH', | |
status: true, | |
payload: 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) // 22 | |
/* 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