All files / src/lib/attributes stringify.ts

4.17% Statements 1/24
0% Branches 0/11
0% Functions 0/3
4.17% Lines 1/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            1x                                                                                
import { Attributes } from ".";
 
/**
 * Convert attributes as JSON object to attributes as string
 * @param attributes
 */
export default function(
  attributes: Attributes,
  addCurlyBrackets: boolean = false,
): string {
  const parts = [];
  for (const key in attributes) {
    if (attributes.hasOwnProperty(key)) {
      parts.push(" ");
      parts.push(`${key}=`);
      const value = attributes[key];
      if (value instanceof Array) {
        parts.push(stringifyArray(value));
      } else {
        parts.push(JSON.stringify(value));
      }
    }
  }
  parts.shift();
  if (addCurlyBrackets) {
    parts.unshift("{");
    parts.push("}");
  }
  return parts.join("");
}
 
function stringifyArray(value: any[]) {
  const parts = ["["];
  value.forEach((v, i) => {
    if (v instanceof Array) {
      parts.push(stringifyArray(v));
    } else {
      parts.push(JSON.stringify(v));
    }
    if (i + 1 !== value.length) {
      parts.push(", ");
    }
  });
  parts.push("]");
  return parts.join("");
}