2
0
mirror of https://github.com/tenrok/BBob.git synced 2026-06-08 17:22:26 +03:00

refactor(parser): jsdoc, move some utility functions to separate files

This commit is contained in:
Nikolay Kostyurin
2019-03-02 22:21:44 +02:00
parent ea8358f145
commit ef6a778f45
3 changed files with 136 additions and 68 deletions
+94
View File
@@ -0,0 +1,94 @@
import {
QUOTEMARK,
BACKSLASH,
} from '@bbob/plugin-helper/lib/char';
/**
* @typedef {Object} CharGrabber
* @property {Function} skip
* @property {Function} hasNext
* @property {Function} isLast
* @property {Function} grabWhile
*/
/**
* Creates a grabber wrapper for source string, that helps to iterate over string char by char
* @param {String} source
* @param {Function} onSkip
* @returns
*/
export const createCharGrabber = (source, { onSkip } = {}) => {
let idx = 0;
const skip = () => {
idx += 1;
if (onSkip) {
onSkip();
}
};
const hasNext = () => source.length > idx;
const getRest = () => source.substr(idx);
const getCurr = () => source[idx];
return {
skip,
hasNext,
isLast: () => (idx === source.length),
grabWhile: (cond) => {
const start = idx;
while (hasNext() && cond(getCurr())) {
skip();
}
return source.substr(start, idx - start);
},
getNext: () => source[idx + 1],
getPrev: () => source[idx - 1],
getCurr,
getRest,
/**
* Grabs rest of string until it find a char
* @param {String} char
* @return {String}
*/
substrUntilChar: (char) => {
const restStr = getRest();
const indexOfChar = restStr.indexOf(char);
if (indexOfChar >= 0) {
return restStr.substr(0, indexOfChar);
}
return '';
},
};
};
/**
* Trims string from start and end by char
* @example
* trimChar('*hello*', '*') ==> 'hello'
* @param {String} str
* @param {String} charToRemove
* @returns {String}
*/
export const trimChar = (str, charToRemove) => {
while (str.charAt(0) === charToRemove) {
str = str.substring(1);
}
while (str.charAt(str.length - 1) === charToRemove) {
str = str.substring(0, str.length - 1);
}
return str;
};
/**
* Unquotes \" to "
* @param str
* @return {String}
*/
export const unquote = str => str.replace(BACKSLASH + QUOTEMARK, QUOTEMARK);