Skip to content

Instantly share code, notes, and snippets.

@bancek
Created December 5, 2016 23:30
Show Gist options
  • Save bancek/95f3761b735ff3c3ff6bb85f038c7729 to your computer and use it in GitHub Desktop.
Save bancek/95f3761b735ff3c3ff6bb85f038c7729 to your computer and use it in GitHub Desktop.
Replace .bind(this); with ES6 instance functions
import os
import re
for base, dirs, files in os.walk('src/app'):
for file in files:
path = os.path.join(base, file)
if file.endswith('.js') || file.endswith('.jsx') || file.endswith('.ts') || file.endswith('.tsx'):
lines = open(path).read().splitlines()
binds = [(i, x) for i, x in enumerate(lines) if '.bind(this);' in x]
if len(binds) == 0:
continue
if lines[binds[0][0]-1] == '':
lines[binds[0][0]-1] = None
for i, _ in binds:
lines[i] = None
lines = [x for x in lines if x is not None]
for _, bind in binds:
name_matches = re.search('this.(\w+) = this.\w+.bind\(this\);', bind)
name = name_matches.group(1)
matches = None
for i, line in enumerate(lines):
matches = re.search('^([ ]+)%s\((.*?)\) \{$' % name, line)
if matches:
break
matches = re.search('^([ ]+)%s\((.*?)\): void \{$' % name, line)
if matches:
break
matches = re.search('^([ ]+)private %s\((.*?)\) \{$' % name, line)
if matches:
break
matches = re.search('^([ ]+)private %s\((.*?)\): void \{$' % name, line)
if matches:
break
matches = re.search('^([ ]+)public %s\((.*?)\) \{$' % name, line)
if matches:
break
matches = re.search('^([ ]+)public %s\((.*?)\): void \{$' % name, line)
if matches:
break
if matches is not None:
lines[i] = '%s%s = (%s) => {' % (matches.group(1), name, matches.group(2))
else:
print 'Not found', path, name
newcontent = '\n'.join(lines)
newcontent.strip()
newcontent += '\n'
open(path, 'w').write(newcontent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment