Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active July 27, 2021 05:48
Show Gist options
  • Save CMCDragonkai/180a12d067a86fbdea4422d4163f56c3 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/180a12d067a86fbdea4422d4163f56c3 to your computer and use it in GitHub Desktop.
Accumulating Parameter Pattern in JavaScript #javascript #typescript
// mutating input and output
const rec = (inputs: Array<number>, outputs: Array<number> = []) => {
if (!inputs.length) {
return outputs;
} else {
const input = inputs.shift()!;
outputs.push(input + 1);
return rec(inputs, outputs);
}
};
console.log(rec([1,2,3,4]));
// constant input and mutating output (this is probably the fastest)
const inputs = [1,2,3,4];
const rec2 = (inputsIndex: number, outputs: Array<number> = []) => {
if (inputsIndex >= inputs.length) {
return outputs;
} else {
const input = inputs[inputsIndex];
outputs.push(input + 1);
return rec2(inputsIndex + 1, outputs);
}
};
console.log(rec2(0));
// immutable input and output
const rec3 = ([input, ...inputs]: Array<number>, outputs: Array<number> = []) => {
if (input == undefined) {
return outputs;
} else {
return rec3(inputs, outputs.concat(input + 1));
}
};
console.log(rec3([1,2,3,4]));
// you can mix and match the above based on performance requirements
// this pattern can be used with callbacks
// which can be necessary to loop sequence asynchronous callbacks
const callback = (e, r) => {
console.log(r);
};
const rec4 = ([input, ...inputs]: Array<number>, outputs: Array<number> = []) => {
if (input == undefined) {
callback(null, outputs);
} else {
setTimeout(() => {
outputs.push(input + 1);
rec4(inputs, outputs);
});
}
};
rec4([1,2,3,4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment