Skip to content

Instantly share code, notes, and snippets.

@righ
Last active June 16, 2020 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save righ/71e32be8e33f74bde516c06f80c941e8 to your computer and use it in GitHub Desktop.
Save righ/71e32be8e33f74bde516c06f80c941e8 to your computer and use it in GitHub Desktop.
Array tools in TypeScript
export const range = (start: number, stop: number, step: number=1) => {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Sequence_generator_(range)
return Array.from({ length: (stop - start - 1) / step + 1}, (_, i) => start + (i * step));
}
export const all = (values: any[]) => {
for (let value of values) {
if (!value) {
return false;
}
}
return true;
}
export const zip = (... lists: [... any[]]): [... any[]] => {
const length = lists[0].length;
return range(0, length).map(i => lists.map(l => l[i]));
}
export const combinations = <T>(list: T[], length: number): T[][] => {
const pairs: T[][] = [];
const set = (pair: T[], index: number) => {
if (pair.length == length) {
pairs.push(pair);
return;
}
for (let i = index; i < list.length; i++) {
set([... pair, list[i]], i + 1);
}
}
set([], 0);
return pairs;
}
export const product = <T>(... list: T[][]): T[][] => {
const pairs: T[][] = [];
const set = (pair: T[], index: number) => {
if (pair.length === list.length) {
pairs.push(pair);
return;
}
for (let i of list[index]) {
set([... pair, i], index + 1);
}
}
set([], 0);
return pairs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment