Некоторое время назад кто-то попросил меня в интервью напечатать «Hello World» в консоли 50 раз без использования цикла. Ответ, очевидно, был с рекурсией. Но был ли это единственный ответ?

После этого я начинаю размышлять… давайте узнаем?

Если хотите проверить: https://github.com/Noriller/js-console.log

Я сделал репозиторий и использовал jest, чтобы проверить, все ли работает, я также использовал эту вспомогательную функцию:

function Log() {
  console.log("Hello World!");
}

Большинство из них были просто вариациями одного и того же… но мне удалось заставить это работать неожиданным образом.

Грубое принуждение!

Потому что… почему бы и нет?

Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log(); Log();

Использование циклов

Хорошо, интервьюер сказал, что никаких петель, но здесь мы можем использовать…

// The classic For Loop
for (let i = 0; i < 50; i++) {
  Log();
}
// Do While Loop
let i = 0;
do {
  Log();
  i++;
} while (i < 50);
// While Loop
let i = 0;
while (i < 50) {
  Log();
  i++;
}
// For Of
const arr = Array(50).fill(Log);
for (let x of arr) {
  x();
}
// For In
const arr = Array(50).fill(Log);
const obj = Object.assign({}, arr);
for (let x in obj) {
  obj[x]();
}

Использование функций массива Javascript

const arr = Array(50).fill(Log);
// Multiple Array Funcions
// Basically the same way...
arr.forEach(el => el());
arr.map(el => el());
arr.filter(el => el());
arr.find(el => el());
arr.findIndex(el => el());
arr.reduce((acc, el) => el(), {});
arr.reduceRight((acc, el) => el(), {});
arr.every(el => !el());
arr.some(el => el());

Немного схожу с ума по методам массива:

// Array From (basically a map)
Array.from(
  Array(50).fill(Log),
  x => x()
);
const arr = Array(50).fill(Log);
// Pop
while (arr.length > 0) {
  arr.pop()();
}
// Shift
while (arr.length > 0) {
  arr.shift()();
}
// Splice
while (arr.length > 0) {
  arr.splice(0, 1)[0]();
}

Использование рекурсии

// Classic Recursion
function Log50(num = 1) {
  if (num > 50) return;
  Log();
  Log50(num + 1);
}
Log50();

Использование времени?

// Set Interval (basically a loop)
let i = 1;
const interval = setInterval(() => {
  if (i > 50) return clearInterval(interval);
  i++;
  Log();
}, 1000);
// Set Timeout (basically recursion)
let i = 1;
function timers() {
  const timeout = setTimeout(() => {
    if (i > 50) return;
    i++;
    Log();
    clearTimeout(timeout);
    timers();
  }, 1000);
}
timers();
// Set Immediate (same as timeout)
let i = 1;
function timers() {
  const immediate = setImmediate(() => {
    if (i > 50) return;
    i++;
    Log();
    clearImmediate(immediate);
    timers();
  });
}
timers();

Попробуй поймать?

class CustomError extends Error {
  constructor(...args) {
    super(...args);
    this.Log50();
  }
  Log50(num = 1) {
    if (num > 50) return;
    Log();
    this.Log50(num + 1);
  }
}
try {
  throw new CustomError();
} catch (error) {
}

Оператор распространения?

function* generator(num = 0) {
  while (num < 50) {
    num++;
    yield Log();
  }
}
[...generator()];

Видите ли… в итоге получается либо цикл, либо рекурсия… в основном это то, как вы это называете…

Но эй ... вы можете придумать другой способ сделать это?

Если вы можете… оставить комментарий или, может быть, отправить PR?

Фото на обложке Markus Spiske на Unsplash