Skip to content

Instantly share code, notes, and snippets.

@artginzburg
Last active September 23, 2021 19:26
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 artginzburg/32b5a624bb22c1127190082dfdbb45dd to your computer and use it in GitHub Desktop.
Save artginzburg/32b5a624bb22c1127190082dfdbb45dd to your computer and use it in GitHub Desktop.
Legal JS quine — no `console.log`, `eval` or reading source code • Test with `$ node test` or just paste into your browser console
($=_=>`($=${$})()`)()
const fs = require('fs');
const quineAsText = fs.readFileSync('./quine.js', 'utf8');
const quineAsFunction = $=_=>`($=${$})()`;
const quineResult = quineAsFunction();
const tests = [
quineAsText,
eval(quineAsText),
quineAsFunction(),
eval(quineAsFunction.toString())(),
$(),
quineResult,
eval(quineResult)
];
console.log(tests);
console.log(tests.every(value => value === tests[0])); // true if quine works

EN | RU

If you need some words instead of pure code, or a Short answer

quine.js meaning, briefly: define a variable with name — dollar sign ($) and assign a function to it. Give first argument of the function name — underscore sign (_). The argument is not actually used inside the function, but it looks good in a quine. Make the function return a string with an expression inside (made possible by wrapping the string in backquotes (`) and wrapping the expression in ${}). The expression calls dollar sign ($), which is the name of the function. Since we don't actually execute dollar sign ($), this is not a recursive call. But when we execute the function, the expression gets replaced with the function we assigned to dollar sign ($). After replacement, the string is returned from the function like about this — 1. beginning part of the string — ($=, 2. our replaced expression — _=>`($=${$})()`, 3. ending part of the string — )().

The following basically means the same as in quine.js. Wouldn't be much of a quine nor a one-liner though :/

var $=function(){return `($=${$})()`};$()

Long answer

The code can be wrapped for understanding as such:

(
  $ =
    _ =>
      `($=${ $ })()`
)
()
  1. ( with ) on lines 1 and 5 are just borders that wrap up a function, making it possible for () on line 6 to "execute it". Such construction is called Immediately-Invoked Function Expression (IIFE).

  2. $ = on line 2 means "define a variable with name $ that equals..."

  3. _ => on line 3 defines an Anonymous Arrow Function with first argument named _ and returning...

Since argument _ is never called in the function and is not given any value when the function is called on line 6, it can be safely omited — replaced by () — without hurting the quine logic.

  1. `($=${ $ })()` on line 4 is a Template Literal defined by covering anything in gravises, also known as backticks (`)

Template Literals (`smth`) allow to include an expression (like an argument's value) inside a String ("smth" or 'smth') by wrapping it in ${}

e.g. instead of 'a city called ' + city + ' is the capital of Great Britain' we could write `a city called ${city} is the capital of Great Britain`

  1. Line 4 calls a variable named $, which takes us back to point 2, where we gave variable $ the following value:
_=>`($=${$})()`
  1. If we needed to represent line 4 as a String without calling any variables, we'd get the following string: ($=)(). Now try copying the code block from point 5 and pasting it between ($= and )(). You see it, right? :)

For better understanding (not a quine)

function dollar(_unused) {
  return "($=" + dollar.toString() + ")()";
}
dollar();

A simpler working quine

(dollar=()=>'(dollar='+dollar+')()')()

EN | RU

Если нужно немного слов вместо чистого кода или Короткий ответ

quine.js вкратце значит: определить переменную с названием — знак доллара ($) и присвоить ей функцию. Дать первому аргументу функции имя — знак нижнего подчёркивания (_). Аргумент не используется внутри функции, зато хорошо смотрится в квайне. Функция должна вернуть строку с выражением внутри (для этого строка заворачивается в грависы (`), а само выражение — в ${}). Выражение вызывает знак доллара ($), который, кстати, и является именем всей функции. Так как знак доллара не выполняется, а лишь вызывается, это не рекурсивный вызов. Тем не менее, при исполнении функции выражение заменяется на саму функцию, которая присвоена знаку доллара ($). После замены, строка возвращается из функции примерно в таком виде — 1. начальная часть строки — ($=, 2. подставленное значение выражения — _=>`($=${$})()`, 3. конечная часть строки — )(). На выходе получается точь-в-точь текст файла quine.js.

Следующий код значит, если говорить только о типах выражений, то же, что quine.js. Хотя, конечно, квайном, или хотя бы однострочником, это не назовёшь :/

var $=function(){return `($=${$})()`};$()

Длинный ответ

Код можно разделить переносами строки для понимания:

(
  $ =
    _ =>
      `($=${ $ })()`
)
()
  1. ( и ) на строках 1 и 5 — просто границы для функции, чтобы затем () на строке 6 означало "выполнить её". Такая конструкция называется "Немедленно вызываемая функция" (IIFE).

  2. $ = на строке 2 значит "определить переменную с именем $ и присвоить ей..."

  3. _ => на строке 3 определяет Анонимную Стрелочную Функцию с первым аргументом, названным _ и возвращающую...

Так как аргумент _ не используется внутри функции и не получает никакого значения во время вызова функции на строке 6, он может быть смело пропущен — заменён на () — без вреда для логики куайна.

  1. `($=${ $ })()` на строке 4 — это Шаблонный Литерал, обозначаемый заключением текста в грависы, также известные как обратные ударения (`)

Шаблонные Строки (`что-нибудь`) позволяют включить выражение (например, значение переменной) внутрь Строки ("что-нибудь" or 'что-нибудь'), завернув его в ${}

например, вместо 'город под названием ' + city + ' — столица Великобритании' можно написать `город под названием ${city} — столица Великобритании`

  1. На четвёртой строке вызывается переменная с названием $, что возвращает нас к пункту 2, где мы дали этой переменной следующее значение:
_=>`($=${$})()`
  1. Будь код на линии 4 обычной Строкой без вызова каких-либо переменных, мы бы получили следующее: ($=)(). Если скопировать блок кода из 5-го пункта и вставить его между ($= и )(), то квайн... Сработал? :)

Перевод на русский для упрощения

функция доллар(_неИспользуется) {
  вернуть "(доллар=" + доллар + ")()";
}
доллар();

Ещё один лёгкий рабочий куайн

(dollar=()=>'(dollar='+dollar+')()')()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment