UNPKG

parallel-es

Version:
51 lines (42 loc) 2.56 kB
import {IParallelGenerator} from "./parallel-generator"; import {FunctionCallSerializer} from "../../function/function-call-serializer"; import {ISerializedFunctionCall} from "../../function/serialized-function-call"; import {ParallelWorkerFunctionIds} from "../slave/parallel-worker-functions"; import {FunctionCall} from "../../function/function-call"; import {IParallelTaskEnvironment} from "../"; import {IFunctionId, isFunctionId} from "../../function/function-id"; /** * Generic generator that calls a passed in function n times to create n values */ export class ParallelTimesGenerator implements IParallelGenerator { public static create<TResult>(n: number, generator: (this: void, index: number, env: IParallelTaskEnvironment) => TResult): ParallelTimesGenerator; public static create<T>(n: number, value: T): ParallelTimesGenerator; public static create(n: number, call: FunctionCall): ParallelTimesGenerator; public static create<T>(n: number, generator: ((this: void, index: number, env: IParallelTaskEnvironment) => T) | IFunctionId | T): ParallelTimesGenerator { let generatorFunction: FunctionCall; if (isFunctionId(generator) || typeof generator === "function") { generatorFunction = FunctionCall.createUnchecked(generator); } else { generatorFunction = FunctionCall.create(ParallelWorkerFunctionIds.IDENTITY, generator); } return new ParallelTimesGenerator(n, generatorFunction); } public readonly times: number; public readonly iteratee: FunctionCall; /** * Creates a new times generator that repeats the value generated by the iteratee n times. * @param n the number of times the value should be repeated * @param iteratee function that is called n times and generates the value or a constant value that is repeated */ private constructor(n: number, iteratee: FunctionCall) { this.times = n; this.iteratee = iteratee; } get length(): number { return this.times; } public serializeSlice(index: number, numberOfItems: number, functionCallSerializer: FunctionCallSerializer): ISerializedFunctionCall { const sliceStart = index * numberOfItems; const sliceEnd = Math.min(sliceStart + numberOfItems, this.times); const iterateeFunction = functionCallSerializer.serializeFunctionCall(this.iteratee); return functionCallSerializer.serializeFunctionCall(FunctionCall.create(ParallelWorkerFunctionIds.TIMES, sliceStart, sliceEnd, iterateeFunction)); } }