Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80540 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
25
// TODO: This is a pretty massive helper, it should only be defined once, in the
26
// transform's runtime environment. We don't currently have a runtime though.
27
var restFunction =
28
'(function(source, exclusion) {' +
29
'var rest = {};' +
30
'var hasOwn = Object.prototype.hasOwnProperty;' +
31
'if (source == null) {' +
32
'throw new TypeError();' +
33
'}' +
34
'for (var key in source) {' +
35
'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' +
36
'rest[key] = source[key];' +
37
'}' +
38
'}' +
39
'return rest;' +
40
'})';
41
42
function getPropertyNames(properties) {
43
var names = [];
44
for (var i = 0; i < properties.length; i++) {
45
var property = properties[i];
46
if (property.type === Syntax.SpreadProperty) {
47
continue;
48
}
49
if (property.type === Syntax.Identifier) {
50
names.push(property.name);
51
} else {
52
names.push(property.key.name);
53
}
54
}
55
return names;
56
}
57
58
function getRestFunctionCall(source, exclusion) {
59
return restFunction + '(' + source + ',' + exclusion + ')';
60
}
61
62
function getSimpleShallowCopy(accessorExpression) {
63
// This could be faster with 'Object.assign({}, ' + accessorExpression + ')'
64
// but to unify code paths and avoid a ES6 dependency we use the same
65
// helper as for the exclusion case.
66
return getRestFunctionCall(accessorExpression, '{}');
67
}
68
69
function renderRestExpression(accessorExpression, excludedProperties) {
70
var excludedNames = getPropertyNames(excludedProperties);
71
if (!excludedNames.length) {
72
return getSimpleShallowCopy(accessorExpression);
73
}
74
return getRestFunctionCall(
75
accessorExpression,
76
'{' + excludedNames.join(':1,') + ':1}'
77
);
78
}
79
80
exports.renderRestExpression = renderRestExpression;
81
82