Home Reference Source

src/utils/attr-list.js

  1. const DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
  2. const ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
  3.  
  4. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  5. class AttrList {
  6. constructor (attrs) {
  7. if (typeof attrs === 'string') {
  8. attrs = AttrList.parseAttrList(attrs);
  9. }
  10.  
  11. for (let attr in attrs) {
  12. if (attrs.hasOwnProperty(attr)) {
  13. this[attr] = attrs[attr];
  14. }
  15. }
  16. }
  17.  
  18. decimalInteger (attrName) {
  19. const intValue = parseInt(this[attrName], 10);
  20. if (intValue > Number.MAX_SAFE_INTEGER) {
  21. return Infinity;
  22. }
  23.  
  24. return intValue;
  25. }
  26.  
  27. hexadecimalInteger (attrName) {
  28. if (this[attrName]) {
  29. let stringValue = (this[attrName] || '0x').slice(2);
  30. stringValue = ((stringValue.length & 1) ? '0' : '') + stringValue;
  31.  
  32. const value = new Uint8Array(stringValue.length / 2);
  33. for (let i = 0; i < stringValue.length / 2; i++) {
  34. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  35. }
  36.  
  37. return value;
  38. } else {
  39. return null;
  40. }
  41. }
  42.  
  43. hexadecimalIntegerAsNumber (attrName) {
  44. const intValue = parseInt(this[attrName], 16);
  45. if (intValue > Number.MAX_SAFE_INTEGER) {
  46. return Infinity;
  47. }
  48.  
  49. return intValue;
  50. }
  51.  
  52. decimalFloatingPoint (attrName) {
  53. return parseFloat(this[attrName]);
  54. }
  55.  
  56. enumeratedString (attrName) {
  57. return this[attrName];
  58. }
  59.  
  60. decimalResolution (attrName) {
  61. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  62. if (res === null) {
  63. return undefined;
  64. }
  65.  
  66. return {
  67. width: parseInt(res[1], 10),
  68. height: parseInt(res[2], 10)
  69. };
  70. }
  71.  
  72. static parseAttrList (input) {
  73. let match, attrs = {};
  74. ATTR_LIST_REGEX.lastIndex = 0;
  75. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  76. let value = match[2], quote = '"';
  77.  
  78. if (value.indexOf(quote) === 0 &&
  79. value.lastIndexOf(quote) === (value.length - 1)) {
  80. value = value.slice(1, -1);
  81. }
  82.  
  83. attrs[match[1]] = value;
  84. }
  85. return attrs;
  86. }
  87. }
  88.  
  89. export default AttrList;