Dotclear

source: inc/js/util.js @ 4002:8179279ed508

Revision 4002:8179279ed508, 1.3 KB checked in by franck <carnet.franck.paul@…>, 6 years ago (diff)

Doc and some utils JS for public part

Line 
1/*exported getData, isObject, mergeDeep */
2'use strict';
3
4var getData = getData || function(id, clear = true) {
5  let data = {};
6  // Read the JSON-formatted data from the DOM. (from https://mathiasbynens.be/notes/json-dom-csp)
7  // To be use with: <script type="application/json" id="myid-data">{"key":value, …}</script>
8  const element = document.getElementById(`${id}-data`);
9  if (element) {
10    try {
11      data = JSON.parse(element.textContent);
12      if (clear) {
13        // Clear the element’s contents
14        element.innerHTML = '';
15      }
16    } catch (e) {}
17  }
18  return data;
19};
20
21var isObject = isObject || function isObject(item) {
22  return (item && typeof item === 'object' && !Array.isArray(item));
23};
24
25/**
26 * Deep merge two objects.
27 * @param target
28 * @param ...sources
29 */
30var mergeDeep = mergeDeep || function mergeDeep(target, ...sources) {
31  if (!sources.length) return target;
32  const source = sources.shift();
33  if (isObject(target) && isObject(source)) {
34    for (const key in source) {
35      if (isObject(source[key])) {
36        if (!target[key]) Object.assign(target, { [key]: {} });
37        mergeDeep(target[key], source[key]);
38      } else {
39        Object.assign(target, { [key]: source[key] });
40      }
41    }
42  }
43  return mergeDeep(target, ...sources);
44};
Note: See TracBrowser for help on using the repository browser.

Sites map