Skip to content

Instantly share code, notes, and snippets.

@smashwilson
Created May 2, 2018 17:10
Show Gist options
  • Save smashwilson/dbc0f072701b412c05f2dcc205448c63 to your computer and use it in GitHub Desktop.
Save smashwilson/dbc0f072701b412c05f2dcc205448c63 to your computer and use it in GitHub Desktop.
Init script to refactor @autoBind to autobind helper calls
atom.commands.add('atom-text-editor', 'me:copy-autobinds', event => {
const editor = event.target.closest('atom-text-editor').getModel()
const text = editor.getText();
const methodNames = [];
const rx = /@autobind\s*(async\s*)?([a-zA-Z_]+)/g
let match = rx.exec(text)
while (match !== null) {
methodNames.push(match[2])
match = rx.exec(text)
}
if (methodNames.length > 0) {
let snippet = 'autobind(this, ' + methodNames.map(m => `'${m}'`).join(', ') + ');'
if (snippet.length > 116) {
// Wrapping needed
snippet = 'autobind(\n this,\n '
let lineLength = 6
for (const methodName of methodNames) {
const quoted = `'${methodName}',`
if (lineLength + quoted.length > 120) {
snippet += '\n '
lineLength = 6
}
if (lineLength !== 6) {
snippet += ' '
lineLength++
}
snippet += quoted
lineLength += quoted.length
}
snippet += '\n );'
}
atom.clipboard.write(snippet)
const plural = methodNames.length === 1 ? '' : 's'
atom.notifications.addSuccess(`${methodNames.length} autobind method${plural} copied.`)
} else {
atom.notifications.addWarning('No autobind methods discovered.')
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment