Skip to content

Instantly share code, notes, and snippets.

@TheEnquirer
Created May 23, 2022 21:37
Show Gist options
  • Save TheEnquirer/18cbb8fc6308b0478b2cc7e10a9c8795 to your computer and use it in GitHub Desktop.
Save TheEnquirer/18cbb8fc6308b0478b2cc7e10a9c8795 to your computer and use it in GitHub Desktop.
Some attempts at python style list comprehension in js
// ##########################################################
// pythonic list comprehension in js
// (as a toy task to test out github.com/metakirby5/codi.vim)
// ##########################################################
// ####################################
// first method: ~rust style. heavy WIP
// ####################################
String.prototype.for = function(inp) {
return inp.map(eval("x => " + this))
}
Array.prototype.if = function(inp) {
return this.filter(eval("x =>" + inp))
}
// ###### driver code ######
let arr = [1, 2, 3, 4, 5, 6, 7]
let out = 'x+1'.for(arr).if('x > 5')
// #############################
// second method: true pythonic!
// #############################
function c(str) {
let condIdx = str.indexOf('if')
let stoppingIdx = condIdx
let cond = str.slice(condIdx+2)
let arr = str.slice(str.indexOf("in") +2, stoppingIdx)
let mod = str.slice(0, str.indexOf("for"))
let mid = str.slice(str.indexOf("for")+3, str.indexOf("in")).trim()
if (condIdx == -1) {
stoppingId = str.length
cond = true
arr = str.slice(str.indexOf("in") +2)
}
let out = []
const modFunc = eval(mid + " => " + mod)
let toParse = `${arr}.forEach(${mid} => { if (${cond}) out.push(modFunc(${mid.replace(/[()]/g, '')})) })`
eval(toParse)
return out
}
// ###### driver code ######
let a = [0, 1, 2, 3, 4, 5, 6]
let res = c('y+12 for y in a if y < 4')
// > [ 12, 13, 14, 15 ]
let b = [true, false, false, true]
let rrres = c('[i, v] for (v,i) in b')
// > [ [ 0, true ], [ 1, false ], [ 2, false ], [ 3, true ] ]
let strings = ["dog", "orange", "bar"]
let tought = c('x for (x,y) in strings if y > 1')
// > [ 'bar' ]
let s = c(`[ ${c(`[${c('p for p in [1, 2, 3]')}] for l in [1, 2]`)} ] for x in [1, 2, 3]`)
// > [ [ 1, 2, 3, 1, 2, 3 ], [ 1, 2, 3, 1, 2, 3 ], [ 1, 2, 3, 1, 2, 3 ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment