Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81147 views
1
/**
2
* Copyright 2013 Facebook, Inc.
3
*
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
7
*
8
* http://www.apache.org/licenses/LICENSE-2.0
9
*
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
15
*/
16
17
/*jslint node:true*/
18
19
/**
20
* Desugars ES7 rest properties into ES5 object iteration.
21
*/
22
23
var Syntax = require('esprima-fb').Syntax;
24
var utils = require('../src/utils');
25
26
// TODO: This is a pretty massive helper, it should only be defined once, in the
27
// transform's runtime environment. We don't currently have a runtime though.
28
var restFunction =
29
'(function(source, exclusion) {' +
30
'var rest = {};' +
31
'var hasOwn = Object.prototype.hasOwnProperty;' +
32
'if (source == null) {' +
33
'throw new TypeError();' +
34
'}' +
35
'for (var key in source) {' +
36
'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' +
37
'rest[key] = source[key];' +
38
'}' +
39
'}' +
40
'return rest;' +
41
'})';
42
43
function getPropertyNames(properties) {
44
var names = [];
45
for (var i = 0; i < properties.length; i++) {
46
var property = properties[i];
47
if (property.type === Syntax.SpreadProperty) {
48
continue;
49
}
50
if (property.type === Syntax.Identifier) {
51
names.push(property.name);
52
} else {
53
names.push(property.key.name);
54
}
55
}
56
return names;
57
}
58
59
function getRestFunctionCall(source, exclusion) {
60
return restFunction + '(' + source + ',' + exclusion + ')';
61
}
62
63
function getSimpleShallowCopy(accessorExpression) {
64
// This could be faster with 'Object.assign({}, ' + accessorExpression + ')'
65
// but to unify code paths and avoid a ES6 dependency we use the same
66
// helper as for the exclusion case.
67
return getRestFunctionCall(accessorExpression, '{}');
68
}
69
70
function renderRestExpression(accessorExpression, excludedProperties) {
71
var excludedNames = getPropertyNames(excludedProperties);
72
if (!excludedNames.length) {
73
return getSimpleShallowCopy(accessorExpression);
74
}
75
return getRestFunctionCall(
76
accessorExpression,
77
'{' + excludedNames.join(':1,') + ':1}'
78
);
79
}
80
81
exports.renderRestExpression = renderRestExpression;
82
83