react / react-0.13.3 / examples / basic-commonjs / node_modules / reactify / node_modules / jstransform / visitors / es7-rest-property-helpers.js
81147 views/**1* Copyright 2013 Facebook, Inc.2*3* Licensed under the Apache License, Version 2.0 (the "License");4* you may not use this file except in compliance with the License.5* You may obtain a copy of the License at6*7* http://www.apache.org/licenses/LICENSE-2.08*9* Unless required by applicable law or agreed to in writing, software10* distributed under the License is distributed on an "AS IS" BASIS,11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12* See the License for the specific language governing permissions and13* limitations under the License.14*/1516/*jslint node:true*/1718/**19* Desugars ES7 rest properties into ES5 object iteration.20*/2122var Syntax = require('esprima-fb').Syntax;23var utils = require('../src/utils');2425// TODO: This is a pretty massive helper, it should only be defined once, in the26// transform's runtime environment. We don't currently have a runtime though.27var 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'})';4142function getPropertyNames(properties) {43var names = [];44for (var i = 0; i < properties.length; i++) {45var property = properties[i];46if (property.type === Syntax.SpreadProperty) {47continue;48}49if (property.type === Syntax.Identifier) {50names.push(property.name);51} else {52names.push(property.key.name);53}54}55return names;56}5758function getRestFunctionCall(source, exclusion) {59return restFunction + '(' + source + ',' + exclusion + ')';60}6162function 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 same65// helper as for the exclusion case.66return getRestFunctionCall(accessorExpression, '{}');67}6869function renderRestExpression(accessorExpression, excludedProperties) {70var excludedNames = getPropertyNames(excludedProperties);71if (!excludedNames.length) {72return getSimpleShallowCopy(accessorExpression);73}74return getRestFunctionCall(75accessorExpression,76'{' + excludedNames.join(':1,') + ':1}'77);78}7980exports.renderRestExpression = renderRestExpression;818283