const findSep = (value, offset = 0) => {
  const find = value.indexOf('|', offset);
  if (find !== -1) {
    let count = 0;
    let from = find;
    while (value[--from] === '#') ++count;
    if ((count & 1) === 1) {
      return findSep(value, find + 1);
    } else {
      return find;
    }
  } else {
    return -1;
  }
};

const transform = (value) => {
  const find = value.indexOf('#');
  if (find !== -1) {
    const left = value.slice(0, find);
    const me = value[find + 1] ? value[find + 1] : '';
    const right = value.slice(find + 2);
    return `${left}${me}${transform(right)}`;
  } else {
    return value;
  }
};

export const split = (value, unescape = true) => {
  const ret = [];
  let offset = 0;
  let posSep = -1;
  do {
    posSep = findSep(value, offset);
    if (posSep !== -1) {
      if (unescape) {
        ret.push(transform(value.slice(offset, posSep)));
      } else {
        ret.push(value.slice(offset, posSep));
      }
      offset = posSep + 1;
    }
  } while (posSep !== -1);
  if (unescape) {
    ret.push(transform(value.slice(offset)));
  } else {
    ret.push(value.slice(offset));
  }
  return ret;
};

