From 91bf849cc7ca5e0c111f7c689afa607c4f79b44b Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Mon, 3 Apr 2017 21:39:49 -0400 Subject: [PATCH] generate more idiomatic code when removing object properties --- src/utils/removeObjectKey.js | 36 +++++++++++++++---- .../attribute-partial-number/main.html | 12 +++---- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/src/utils/removeObjectKey.js b/src/utils/removeObjectKey.js index a78a5b6ab2..6611dffa40 100644 --- a/src/utils/removeObjectKey.js +++ b/src/utils/removeObjectKey.js @@ -1,9 +1,33 @@ export default function removeObjectKey ( generator, node, key ) { if ( node.type !== 'ObjectExpression' ) return; - const properties = node.properties; - const index = properties.findIndex( property => property.key.type === 'Identifier' && property.key.name === key ); - if ( index === -1 ) return; - const a = properties[ index ].start; - const b = index < properties.length - 1 ? properties[ index + 1 ].start : node.end - 1; - generator.code.remove( a, b ); + + let i = node.properties.length; + while ( i-- ) { + const property = node.properties[i]; + if ( property.key.type === 'Identifier' && property.key.name === key ) { + let a; + let b; + + if ( node.properties.length === 1 ) { + // remove everything, leave {} + a = node.start + 1; + b = node.end - 1; + } else if ( i === 0 ) { + // remove everything before second property, including comments + a = node.start + 1; + while ( /\s/.test( generator.code.original[a] ) ) a += 1; + + b = node.properties[i].end; + while ( /[\s,]/.test( generator.code.original[b] ) ) b += 1; + } else { + // remove the end of the previous property to the end of this one + a = node.properties[ i - 1 ].end; + b = property.end; + } + + generator.code.remove( a, b ); + node.properties.splice( i, 1 ); + return; + } + } } diff --git a/test/generator/samples/attribute-partial-number/main.html b/test/generator/samples/attribute-partial-number/main.html index 7f56dcb447..3910cc093b 100644 --- a/test/generator/samples/attribute-partial-number/main.html +++ b/test/generator/samples/attribute-partial-number/main.html @@ -1,11 +1,11 @@