Last active
June 12, 2016 00:18
-
-
Save gerrard00/e1cdbef9af2c3d2da7e242cb4fc4a931 to your computer and use it in GitHub Desktop.
A little javascript test for rotating arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const delimiterMap = { | |
'[': ']', | |
'(': ')', | |
'<': '>', | |
}; | |
function getArgumentsArray(input) { | |
let current = ''; | |
const result = []; | |
let delimiterEnd; | |
let insideDelimiter = false; | |
for (const c of input) { | |
if (!insideDelimiter && c === ',') { | |
result.push(current); | |
current = ''; | |
continue; | |
} | |
if (c === delimiterEnd) { | |
insideDelimiter = false; | |
} else { | |
insideDelimiter = insideDelimiter || !!(delimiterEnd = delimiterMap[c]); | |
} | |
current += c; | |
} | |
if (current) { | |
result.push(current); | |
} | |
return result; | |
} | |
function shiftArguments(input, direction) { | |
const argumentsArray = getArgumentsArray(input); | |
let argumentToMove; | |
if (argumentsArray.length === 0) { | |
return input; | |
} | |
const spacer = argumentsArray[1].match(/^(\s*)/)[0]; | |
if (direction < 0) { | |
argumentToMove = argumentsArray.shift(); | |
return `${argumentsArray.join(',')},${spacer}${argumentToMove}`.trim(); | |
} | |
argumentToMove = argumentsArray.pop(); | |
return `${argumentToMove.trim()},${spacer}${argumentsArray.join(',')}`; | |
} | |
const input = 'int a, char b, List<int, char> c, int (*add)(int y, int z), bool d'; | |
const forwardResult = shiftArguments(input, 1); | |
const backwardResult = shiftArguments(input, -1); | |
console.log(input); | |
console.log(); | |
console.log(forwardResult); | |
console.log(); | |
console.log(backwardResult); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment