Untitled

 avatar
unknown
typescript
2 years ago
807 B
6
Indexable
function printIdByIndex(strings: string[], index: number) {
  const indexes = new Array(strings.length).fill(0);

  const combinations = strings.reduce((acc, string) => acc * string.length, 1);
  if (index > combinations) {
    return;
  }

  let hasPreviousLeft = false;

  for (let i = strings.length - 1; i >= 0; i--) {
    if (index <= strings[i].length) {
      indexes[i] = hasPreviousLeft ? index : index - 1;
      break;
    }

    let left = index % strings[i].length;

    let position =
      left === 0 ? strings[i].length - 1 : hasPreviousLeft ? left : left - 1;
    indexes[i] = position;

    index = (index - left) / strings[i].length;

    hasPreviousLeft = left !== 0;
  }

  // print id
  console.log(
    indexes.map((position, index) => strings[index].charAt(position)).join('')
  );
}
Editor is loading...