• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * Add properties to object.
3 * @param {Object} obj - The object which need be added properties.
4 * @param {*[]} prop - The properties which to be added.
5 * @return {Object} The object which has been added properties.
6 */
7export function extend(obj, ...prop) {
8  if (typeof Object.assign === 'function') {
9    Object.assign(obj, ...prop);
10  } else {
11    const first = prop.shift();
12    for (const key in first) {
13      obj[key] = first[key];
14    }
15    if (prop.length) {
16      extend(obj, ...prop);
17    }
18  }
19  return obj;
20}
21
22/**
23 * Add or modify a property.
24 * @param {Object} obj - The object which need be added or modified a property.
25 * @param {string} prop - The key of the property.
26 * @param {*} val - The value of the the property.
27 * @param {boolean} [enumerable] - If the property is enumerable.
28 */
29export function def(obj, prop, val, enumerable) {
30  Object.defineProperty(obj, prop, {
31    value: val,
32    enumerable: !!enumerable,
33    writable: true,
34    configurable: true
35  });
36}
37
38
39/**
40 * Remove an item from an array.
41 * @param {*[]} arr - The array from which removes an item.
42 * @param {*} item - The item which to be removed.
43 * @return {*} The item which has been removed.
44 */
45export function remove(arr, item) {
46  if (arr.length) {
47    const index = arr.indexOf(item);
48    if (index >= 0) {
49      return arr.splice(index, 1);
50    }
51  }
52}
53
54/**
55 * Verify whether the property exists or not in object.
56 * @param {Object} obj - The object which should be verified.
57 * @param {string} prop - The property which should be verified.
58 * @return {boolean} The result whether the property exists or not.
59 */
60export function hasOwn(obj, prop) {
61  return Object.prototype.hasOwnProperty.call(obj, prop);
62}
63
64/**
65 * Verify whether a variable is object.
66 * @param {*} any - The variable which should be verified.
67 * @return {boolean} The result whether a variable is an object.
68 */
69export function isObject(any) {
70  return any !== null && typeof any === 'object';
71}
72
73/**
74 * Verify whether a variable is an plain JavaScript object.
75 * @param {*} any - The variable which should be verified.
76 * @return {boolean} The result whether a variable is an plain JavaScript object.
77 */
78export function isPlainObject(any) {
79  return Object.prototype.toString.call(any) === '[object Object]';
80}
81
82/**
83 * Convert ArrayBuffer to Base64.
84 * @param {*} buffer - Binary data buffer.
85 * @return {string} Base64 encoding string.
86 */
87export function bufferToBase64 (buffer) {
88  if (typeof btoa !== 'function') {
89    return '';
90  }
91  const string = Array.prototype.map.call(
92    new Uint8Array(buffer),
93    code => String.fromCharCode(code)
94  ).join('');
95  return btoa(string);
96}