JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Sort of Pythonic JS Array Comprehensions</h1>
<p>
For fun I wanted to use Python style list comprehensions in JS, not because they are needed, not because I thought of a way to implement them that should ever be used, but simply because all your base are belong to me. Here it is:
</p>
<div id="content">
<p>EX1: arrayComp('[god.split(/(\\w)/).reverse().join("") + "!" for god in gods]')</p>
</div>
<div id="content2">
<p>EX2: arrayComp('[x * x for x in nums]')</p>
</div>
<br>
<p>I hope you are glad you you looked :-p</p>
<small>I know eval is evil, and that using strings to add new syntax is silly, but now you can pretend to code in Python, in JS!</small>
CSS
h1, p {
font-family: arial, sans
}
.answer {
color: red;
padding-left: 20px;
}
.input {
color: grey;
padding-left: 20px;
}
JavaScript
function arrayComp (str) {
// Split the statement into it's parts
var parts = str.substring(1,str.length-1).split(/ for | in /);
// Declare a variable to receive the iterable
var myVariable;
// Find and rename the variable (obviously this would fail if it's a substring of any other code currently)
var re = new RegExp(parts[1], 'g');
parts[0] = parts[0].replace(re, 'myVariable');
// Evaluate the iterable creating statement
var iterable = eval(parts[2]);
// Create an array to take the output
var out = [];
// do the iteration
for (var myKey in iterable) {
myVariable = iterable[myKey];
// evaluate the left statement each time
out.push(eval(parts[0]));
}
return out;
};
var content = document.getElementById('content');
var content2 = document.getElementById('content2');
var gods = ['floW', 'noitaslA', 'drehpehS namreG', 'goD egasuaS', 'rodarbaL'];
content.innerHTML += '<p class="input">Input: gods = [' + gods + ']';
content.innerHTML += '<p class="answer">Out: ' + arrayComp('[god.split(/(\\w)/).reverse().join("") + "!" for god in gods]').join(' ') + '</p>';
var nums = [1, 4, 5, 6, 8, 9, 10];
content2.innerHTML += '<p class="input">Input: nums = [' + nums + ']';
content2.innerHTML += '<p class="answer">Out: ' + arrayComp('[x * x for x in nums]') + '</p>';