function foo(hello, world,
how, are,
you) {
}
Now let’s convert that to the following:function foo(parameters) {
var hello = parameters.hello;
var world = parameters.world;
var how = parameters.how;
var are = parameters.are;
var you = parameters.you;
}
Here are the macros I used to do this:let @r='di(iparameters^[/\{^M2o^[kpg`[v`]Jgv:s/\s//g^M0:try|exe "norm! @q"|endtry^MA;^[V:s/,/;\r/g^Mv``='
let @q='ywivar ^[pa = parameters.^[f,^[l@q'
Note that if you copy paste the above into your vimrc it will not work. The ^[
and ^M
found are actually single characters, not two. To input this properly you will need to chord it in input mode with <Ctrl-V>
. So for <Esc>
you would chord <Ctrl+V><Ctrl+[>
So, when I’m inside the parameters of the function, I can hit @r and it will perform the refactoring. Now let’s break it down step by step.
@q The first macro
This is a recursive macro which takes something like
a,b,c
and turns it into var a = p.a,var b = p.b,var c = p.c
. Let’s see how that’s done.yw
i
var
<Esc>
p
Yanks the word and enter insert mode, type var, exit insert mode and paste the just yanked word.a
= parameters.
Append and fill in parameters.<Esc>
f,
l
Exit insert mode, first the next ,l
@q
Adjust the cursor position and recursively call itself.
@r The second macro
The is the macro that should be invoked, and references the @q macro.
di(
Deletes everything inside the brackets.i
parameters
Enter insert mode and type parameters.<Esc>
/{
<CR>
Leaves insert mode and finds the next brace.2o
<Esc>
k
p
Creates two empty lines and pastes what we deleted into the first line.g`[v`]
J
Visually select what we just pasted and join them all into a single line.gv
:s/\s//g
<CR>
Reselect the visually and delete all whitespace.0
Move to the beginning of the line.:try|exe "norm! @q"|endtry
<CR>
Macros will terminate on the first error, even if referencing another macro. Wrapping the other macro with try|endtry swallows the error and lets the current macro continue.A;
<Esc>
Append ; to the end of the line.V
:s/,/;\r/g
<CR>
Visually select the line, replace with carriage returns.v=` `
Visually select from the current cursor position back to where it was originally was, and format.
I posted this on vimgolf so let’s see how other people solved the same refactoring!
1 comment:
This is a good article & good site.Thank you for sharing this article. It is help us following categorize:
healthcare, e commerce, programming, it consulting, retail, manufacturing, CRM, digital supply chain management, Delivering high-quality service for your business applications,
Solutions for all Industries,
Getting your applications talking is the key to better business processes,
Rapid web services solutions for real business problems,
Web-based Corporate Document Management System,
Outsourcing Solution,
Financial and Operations Business Intelligence Solution
Post a Comment