all files / sparql/ triple.js

98.51% Statements 66/67
86.49% Branches 32/37
100% Functions 7/7
96.55% Lines 28/29
6 statements, 7 branches Ignored     
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 53 54 55 56 57 58 59 60 61 62 63 64                                                                    29× 28×   27×    
'use strict';
 
export default class Triple {
    /**
     * Represents a SPARQL triple (including object- and predicate-object-lists)
     *
     * @class Triple
     * @constructor
     * @param {String|Array} args - Either one (complete triple string) or three (separate subject, predicate, object) strings. Additionally, a string and an array can be supplied to create object- or predicate-object-lists.
     */
    constructor(...args) {
        var splitTriple = null;
        switch (args.length) {
            case 3:
                let valid = true;
                for (let arg of args) {
                    valid = typeof arg === 'string';
                }
                Eif (valid) splitTriple = args;
                break;
            case 2:
                Eif (typeof args[0] === 'string' && Array.isArray(args[1])) {
                    let params = args[0].split(' ');
                    if (params.length === 2) {
                        // both subject and predicate were given
                        // we have an object list
                        splitTriple = [params[0], params[1], args[1]];
                    } else Eif (params.length === 1) {
                        // only subject was given
                        // this is an object-predicate list
                        splitTriple = [params[0], args[1], null];
                    }
                }
                break;
            case 1:
                Eif (typeof args[0] === 'string') {
                    splitTriple = args[0].split(' ');
                }
                break;
        }
        Eif (Array.isArray(splitTriple)) {
            this.subject = splitTriple[0];
            this.predicate = splitTriple[1];
            this.object = splitTriple[2];
        } else {
            throw new Error('Triple: Wrong argument count or malformed input');
        }
    }
 
    /**
     * Retrieves the SPARQL string representation of the current instance
     *
     * @method toString
     * @returns {String}
     */
    toString() {
        if (Array.isArray(this.predicate)) {
            return `${this.subject} ${this.predicate.join(' ; ')}`;
        } else if (Array.isArray(this.object)) {
            return `${this.subject} ${this.predicate} ${this.object.join(' , ')}`;
        }
        return `${this.subject} ${this.predicate} ${this.object}`;
    }
}