js заметки

/* Точная проверка на число, */
function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

/* Поиск по значению объекта */
function findValue(o, value) {
    for (let prop in o) {
        if (o.hasOwnProperty(prop) && o[prop] === value) {
            return prop;
        }
    }
    return null;
}

/* Проверка на наличие слов исключений через запятую */
function postExcludes(description) {
    let isMatch = false;
    if (settings.exclude) {
        let excludes = settings.exclude.split(',');
        isMatch = excludes.some(function(exclude) {
            let regex = new RegExp(exclude.trim(), "i");
            return regex.test(description);
        });
    }
    return (isMatch);
}

/* Поиск объекта в массиве объектов и получение индекса в массиве */
findSelectedItemIndex():number {
  let obj = this.items.find(x => JSON.stringify(x) === JSON.stringify(this.selectedItem));
  let index = this.items.indexOf(obj);
  return index;
}

/* Динамическая загрузка файла JS через промис */
function loadScript(url) {
  return new Promise(function(resolve, reject) {
    var script = document.createElement('script');
    script.async = true;
    script.src = url;
    // trigger fulfilled state when script is ready
    script.onload = resolve;
    // trigger rejected state when script is not found
    script.onerror = reject;
    document.head.appendChild(script);   
  });
}
// вызов
loadScript('/assets/scripts/app.js').then(initApp);

/* Динамическая загрузка файла JS через колбэк */
function loadScript(url, callback)
{
    var script = document.createElement('script');
    script.async = true;
    script.src = url;
    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;
    document.body.appendChild(script);
}

/* Element has scrollbars */
let div = document.getElementById('container_div_id');
let hasHorizontalScrollbar = div.scrollWidth > div.clientWidth;
let hasVerticalScrollbar = div.scrollHeight > div.clientHeight;

/* Ожидание появления элемента */
function waitForElementRender(elementSelector, callback) {
    var elements = document.querySelectorAll(elementSelector);

    if (elements && elements.length) {
        callback(elements);
    } else {
        setTimeout(function() {
            waitForElementRender(elementSelector, callback);
        }, 50);
    }
}
waitForElementRender('#add-button', function(elements) {
    $(elements).on('click', function(event) {
        openDialog();
    });
});

// Array filtering on multiple fields
/*
var arr = [
  { shape: 'square', color: 'red', used: 1, instances: 1 },
  { shape: 'square', color: 'red', used: 2, instances: 1 },
  { shape: 'circle', color: 'blue', used: 0, instances: 0 },
  { shape: 'square', color: 'blue', used: 4, instances: 4 },
  { shape: 'circle', color: 'red', used: 1, instances: 1 },
  { shape: 'circle', color: 'red', used: 1, instances: 0 },
  { shape: 'square', color: 'red', used: 4, instances: 4 },
  { shape: 'square', color: 'red', used: 2, instances: 2 }
];
globalFilter(arr, 'blue');
*/
 function globalFilter(data, filterValue) {
    if (filterValue) {
      return data.filter(item => Object.keys(item).map((key) => {
        return item[key].toString().toLowerCase().slice(0, filterValue.length) === filterValue.toLowerCase();
      }).includes(true));
    }
  }

// flatten tree to tree
buildTree(list) {
  const map = {};
  const roots = [];
  for (let i = 0; i < list.length; i++) {
    map[list[i].id] = i; // initialize the map
    list[i].children = []; // initialize the children
  }
  for (let i = 0; i < list.length; i++) {
    const node = list[i];
    if (node.parentId !== 0) {
      // if you have dangling branches check that map[node.parentId] exists
      list[map[node.parentId]].children.push(node);
    } else {
      roots.push(node);
    }
  }
  return roots;
}

// Find tree node. Sample: getNode(nodes, 'name', name)
getNode(array, prop, value) {
  function findNode(a, i, o) {
    if (a[prop] === value) {
      node = o[i];
      return true;
    }
    return Array.isArray(a.children) && a.children.some(findNode);
  }
  let node;
  array.some(findNode);
  return node;
}

// max z-index
export function maxZIndex() {
  return Array.from(document.querySelectorAll('body *'))
    .map(a => parseFloat(window.getComputedStyle(a).zIndex))
    .filter(a => !isNaN(a))
    .sort((a, b) => a - b)
    .pop();
}