Skip to content

Instantly share code, notes, and snippets.

@gerrard00
Last active June 12, 2016 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerrard00/e1cdbef9af2c3d2da7e242cb4fc4a931 to your computer and use it in GitHub Desktop.
Save gerrard00/e1cdbef9af2c3d2da7e242cb4fc4a931 to your computer and use it in GitHub Desktop.
A little javascript test for rotating arguments
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