all files / semantic-graphql/src/utils/ getIriLocalName.js

72.22% Statements 26/36
58.33% Branches 14/24
100% Functions 2/2
82.76% Lines 24/29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52   28× 28×   28×         45× 24×   24× 24×   24× 24×   24×   24× 20×   20×                                  
const pound = '#';
const slash = '/';
const colon = ':';
const memory = {};
 
function sliceOrFail(string, sep) {
  const array = string.split(sep);
  const l = array.length;
 
  return l < 2 ? null : array[l - 1];
}
 
// Extracts the localName of an IRI
// Algo inspired by http://rdf4j.org/javadoc/latest/org/eclipse/rdf4j/model/IRI.html
function getIriLocalName(iri) {
  if (memory[iri]) return memory[iri]; // !
  Iif (!(typeof iri === 'string' && iri.includes(colon))) throw new Error(`Given IRI "${iri}" is invalid`);
 
  let workingIri = iri;
  const protocolArray = iri.split('://');
 
  Iif (protocolArray.length > 2) throw new Error(`Given IRI "${iri}" is invalid`);
  Eif (protocolArray.length > 1) workingIri = protocolArray[1];
 
  const resPound = sliceOrFail(workingIri, pound);
 
  if (typeof resPound === 'string') {
    Iif (!resPound.length) throw new Error(`Given IRI "${iri}" is invalid`);
 
    return memory[iri] = resPound;
  }
 
  const resSlash = sliceOrFail(workingIri, slash);
 
  Eif (typeof resSlash === 'string') {
    Iif (!resSlash.length) throw new Error(`Given IRI "${iri}" is invalid`);
 
    return memory[iri] = resSlash;
  }
  const resColon = sliceOrFail(workingIri, colon);
 
  if (typeof resColon === 'string') {
    if (!resColon.length) throw new Error(`Given IRI "${iri}" is invalid`);
 
    return memory[iri] = resColon;
  }
 
  throw new Error(`Given IRI "${iri}" is invalid`);
}
 
module.exports = getIriLocalName;