iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📝

[JavaScript Quine] I wrote a program that outputs its own source code

に公開

I wrote some JavaScript code that outputs its own source code. This is known as a Quine.

I don't use fs.readFile.

If you think this sounds interesting, please try it yourself before reading further.

Resulting Code

const quote = String.fromCharCode(96)
const unzip = str => {
  return str + 'console.log(unzip(' + quote + str + quote + '))'
}
console.log(unzip(`
const quote = String.fromCharCode(96)
const unzip = str => {
  return str + 'console.log(unzip(' + quote + str + quote + '))'
}
`))

Explanation

Following the execution might make your head spin a bit, but it's surprisingly simple.

First, the two red-framed areas are the exact same code. The function above outputs the whole thing.

The blue frame is the part that outputs the rest.

The purple section is there because writing a backtick directly inside the template literal (heredoc) below would cause a syntax error. Therefore, I've designed the function above to output a backtick without actually using one.

In the end, I was able to output everything in the sequence: red, blue, purple, red, purple, and blue.

Video

A video of me attempting the challenge.

https://www.youtube.com/watch?v=_FD4l394JHc&t=468s

Minimal Code

If you minimize it using the same method, it results in the following single line.

q = String.fromCharCode(34);m = s => s + ';console.log(m(' + q + s + q + '))';console.log(m("q = String.fromCharCode(34);m = s => s + ';console.log(m(' + q + s + q + '))'"))

Another example.

m = s => s + ';console.log(m(' + (q = String.fromCharCode(34)) + s + q + '))';console.log(m("m = s => s + ';console.log(m(' + (q = String.fromCharCode(34)) + s + q + '))'"))

GitHubで編集を提案

Discussion