Skip to content

Commit

Permalink
polyfill Object.hasOwn() #209
Browse files Browse the repository at this point in the history
  • Loading branch information
samualtnorman committed Nov 23, 2024
1 parent 52a588b commit 698da0d
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/processScript/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ export function transform(
}

let needGetPrototypeOf = false
let needHasOwn = false

if (program.scope.hasGlobal(`Object`)) {
for (const referencePath of getReferencePathsToGlobal(`Object`, program)) {
Expand All @@ -243,6 +244,9 @@ export function transform(
if (referencePath.parent.property.name == `getPrototypeOf`) {
referencePath.parentPath.replaceWith(t.identifier(`_${uniqueId}_GET_PROTOTYPE_OF_`))
needGetPrototypeOf = true
} else if (referencePath.parent.property.name == `hasOwn`) {
referencePath.parentPath.replaceWith(t.identifier(`_${uniqueId}_HAS_OWN_`))
needHasOwn = true
}
}
}
Expand Down Expand Up @@ -568,6 +572,31 @@ export function transform(
]))
}

if (needHasOwn) {
mainFunction.body.body.unshift(t.variableDeclaration(`let`, [
t.variableDeclarator(
t.identifier(`_${uniqueId}_HAS_OWN_`),
t.callExpression(
t.memberExpression(
t.memberExpression(
t.identifier(
globalFunctionsUnder7Characters.find(name => !program.scope.hasOwnBinding(name))!
),
t.identifier(`call`)
),
t.identifier(`bind`)
),
[
t.memberExpression(
t.memberExpression(t.identifier(`Object`), t.identifier(`prototype`)),
t.identifier(`hasOwnProperty`)
)
]
)
)
]))
}

if (consoleMethodsReferenced.size) {
mainFunction.body.body.unshift(t.variableDeclaration(
`let`,
Expand Down

0 comments on commit 698da0d

Please sign in to comment.