UNPKG

2.12 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 *
8 * @format
9 */
10'use strict';
11/**
12 * Given a object of nested properties, return JavaScript text that would merge
13 * in an object named `objectName` by a series of individual assignments.
14 */
15
16function deepMergeAssignments(objectName, properties) {
17 var assignments = [];
18 collectAssignmentsInto(assignments, [], properties);
19 var jsAssignments = assignments.map(function (_ref) {
20 var path = _ref.path,
21 value = _ref.value;
22 return formatJSAssignment(objectName, path, value);
23 });
24 return jsAssignments.length === 0 ? '' : jsAssignments.join('\n');
25} // Recursively collect assignments
26
27
28function collectAssignmentsInto(assignments, parentPath, parentValue) {
29 // Iterate over the entries in the array or object.
30 forEach(parentValue, function (value, key) {
31 // The "path" is the sequence of keys to arrive at this assignment.
32 var path = parentPath.concat(key); // For each entry, either add an assignment or recurse.
33
34 if (typeof value === 'object' && value !== null) {
35 collectAssignmentsInto(assignments, path, value);
36 } else {
37 assignments.push({
38 path: path,
39 value: value
40 });
41 }
42 });
43} // Print a path/value pair as a JS assignment expression.
44
45
46function formatJSAssignment(objectName, path, value) {
47 var assignmentPath = path.map(function (p) {
48 return typeof p === 'string' ? ".".concat(p) : "[".concat(p, "]");
49 }).join('');
50 var jsValue = value === undefined ? 'undefined' : JSON.stringify(value);
51 return "".concat(objectName).concat(assignmentPath, " = ").concat(jsValue, ";");
52} // Utility for looping over entries in both Arrays and Objects.
53
54
55function forEach(value, fn) {
56 if (Array.isArray(value)) {
57 for (var i = 0; i < value.length; i++) {
58 fn(value[i], i);
59 }
60 } else {
61 for (var k in value) {
62 if (value.hasOwnProperty(k)) {
63 fn(value[k], k);
64 }
65 }
66 }
67}
68
69module.exports = deepMergeAssignments;
\No newline at end of file