JS: very small but very useful

102 views
Skip to first unread message

Val K

unread,
May 6, 2016, 11:26:43 AM5/6/16
to web...@googlegroups.com
Very small py-function that wraps any js-content in anonymous js-function

def JS_fun(*args_lst):
   
def _inner(body):
       
return "(function(%s){ %s ;})" % (','.join(args_lst), body)
   
return _inner


>>> JS_fun( 'a', 'b' )( 'console.log(a,b)' )
'(function(a,b){ console.log(a, b) ;})'


>>> args= ['a', 'b']
>>> JS_fun(*args)('console.log(%s)' % ','.join(args))
'(function(a,b){ console.log(a, b) ;})'

>>> JS_call = lambda f: lambda *args: f + '(%s)' % ','.join([str(a) for a in args])
>>> JS_call( JS_fun('a', 'b')('console.log(a,b)') )('"text"', 123 )
'(function(a,b){ console.log(a,b) ;})("text", 123)'




another smarter variant:

def JS_fun(*args_lst):
    def _inner(*body):
        return "(function(%s){ %s ;})" % (','.join(args_lst), '\n    '.join(body))
    return _inner


#so, you can:
f = JS_fun('a', 'b')(
       'var sum = a+b;', 
       'console.log(sum);',
       'return sum'
)







eric cuver

unread,
May 7, 2016, 2:17:36 AM5/7/16
to web2py-users
you can give us  the website link 

Kenneth

unread,
May 7, 2016, 1:02:40 PM5/7/16
to web2py-users
Could you provide any cases to use this JS function for?
Reply all
Reply to author
Forward
0 new messages