import warning from 'warning';
var calculateExtendedSelection = function (map, selection, step) {
    if (selection.direction === 'backward') {
        return {
            start: CursorHelper.calculatePosition(map, selection.start, step),
            end: selection.end,
            direction: 'backward',
        };
    }
    return {
        start: selection.start,
        end: CursorHelper.calculatePosition(map, selection.end, step),
        direction: 'forward',
    };
};
var CursorHelper = /** @class */ (function () {
    function CursorHelper() {
    }
    CursorHelper.normalizePosition = function (map, position) {
        return map[Math.min(Math.max(0, position), map.length - 1)];
    };
    CursorHelper.calculatePosition = function (map, position, step) {
        if (position < 0 || map.length <= position) {
            warning(false, "position out of range [".concat(0, " .. ").concat(map.length - 1, "], actual value: ").concat(position));
            return position < 0 ? 0 : map.length - 1;
        }
        var raw = CursorHelper.toRawPosition(map, position);
        return CursorHelper.toFormattedPosition(map, raw + step);
    };
    CursorHelper.extendSelection = function (map, selection, step) {
        var normalizedSelection = CursorHelper.normalizeSelection(map, selection);
        return CursorHelper.normalizeSelection(map, calculateExtendedSelection(map, normalizedSelection, step));
    };
    CursorHelper.normalizeSelection = function (map, selection) {
        var start = CursorHelper.normalizePosition(map, selection.start);
        var end = CursorHelper.normalizePosition(map, selection.end);
        if (start === end) {
            return {
                start: start,
                end: end,
                direction: 'none',
            };
        }
        if (start < end) {
            return {
                start: start,
                end: end,
                direction: selection.direction === 'backward' ? 'backward' : 'forward',
            };
        }
        return {
            start: end,
            end: start,
            direction: selection.direction === 'backward' ? 'forward' : 'backward',
        };
    };
    CursorHelper.toRawPosition = function (map, formattedPosition) {
        var count = Math.min(Math.max(0, formattedPosition), map.length - 1);
        return new Set(map.slice(0, count + 1)).size - 1;
    };
    CursorHelper.toFormattedPosition = function (map, rawPosition) {
        var count = Math.max(0, rawPosition) + 1;
        var unique = new Set();
        for (var _i = 0, map_1 = map; _i < map_1.length; _i++) {
            var position = map_1[_i];
            unique.add(position);
            if (unique.size === count) {
                return position;
            }
        }
        return map[map.length - 1];
    };
    return CursorHelper;
}());
export { CursorHelper };
//# sourceMappingURL=CursorHelper.js.map