core-types
Version:
Generic type declarations for e.g. TypeScript, GraphQL and JSON Schema
86 lines (85 loc) • 2.63 kB
JavaScript
import { isNonNullable } from './util.js';
export function positionToLineColumn(text, pos) {
const line = text.slice(0, pos).split("\n").length;
const columnIndex = text.lastIndexOf("\n", pos);
return columnIndex === -1
? { offset: pos, line, column: pos }
: { offset: pos, line, column: pos - columnIndex };
}
export function locationToLineColumn(text, loc) {
if (typeof loc.start === 'object')
return loc;
return {
start: typeof loc.start === 'undefined'
? undefined
: positionToLineColumn(text, loc.start),
...(loc.end == null
? {}
: { end: positionToLineColumn(text, loc.end) }),
};
}
export function getPositionOffset(pos) {
if (typeof pos === 'undefined')
return pos;
else if (typeof pos === 'number')
return pos;
return pos.offset;
}
/**
* Use the smallest {start} and the biggest {end} to make a range consiting of
* all locations
*/
export function mergeLocations(locations) {
let low;
let high;
const getOffset = (loc) => typeof loc === 'number' ? loc : loc?.offset;
locations
.filter(isNonNullable)
.forEach(({ start, end }) => {
const startOffset = getOffset(start);
const endOffset = getOffset(end);
if (startOffset !== undefined) {
if (!low
||
typeof low.location === 'number'
&&
low.location === startOffset
||
low.offset > startOffset)
low = {
location: start,
offset: startOffset,
};
}
if (endOffset !== undefined) {
if (!high
||
typeof high.location === 'number'
&&
high.location === startOffset
||
high.offset < endOffset)
high = {
location: end,
offset: endOffset,
};
}
});
const start = low?.location;
const end = high?.location;
if (typeof start === 'undefined' && typeof end === 'undefined')
return undefined;
if (typeof start?.offset !== 'undefined'
&&
(typeof end?.offset !== 'undefined'
||
typeof end === 'undefined'))
return {
start: start,
end: end,
};
return {
start: getOffset(start) ?? 0,
end: getOffset(end),
};
}