Skip to content

Commit 5b32f11

Browse files
committed
perf: prefer find over filter
also removed hydrateScript since there is not any test using it
1 parent 03e181f commit 5b32f11

File tree

1 file changed

+14
-41
lines changed

1 file changed

+14
-41
lines changed

src/index.js

Lines changed: 14 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -22,64 +22,37 @@ const createGetData = fetch => async (url, opts) => {
2222
const embed = parse(text)
2323

2424
const scripts = embed
25-
.filter(e => e.tagName === 'html')[0]
26-
.children.filter(e => e.tagName === 'body')[0]
27-
.children.filter(e => e.tagName === 'script')
25+
.find(el => el.tagName === 'html')
26+
.children.find(el => el.tagName === 'body')
27+
.children.filter(({ tagName }) => tagName === 'script')
2828

29-
const resourceScriptOld = scripts.filter(
30-
e => e.attributes.findIndex(a => a.value === 'resource') !== -1
29+
let script = scripts.find(script =>
30+
script.attributes.some(({ value }) => value === 'resource')
3131
)
3232

33-
if (resourceScriptOld.length > 0) {
33+
if (script !== undefined) {
3434
// found data in the older embed style
35-
return JSON.parse(
36-
decodeURIComponent(resourceScriptOld[0].children[0].content)
37-
)
35+
return normalizeData({
36+
data: JSON.parse(decodeURIComponent(script.children[0].content))
37+
})
3838
}
3939

40-
const resourceScriptNew = scripts.filter(
41-
e => e.attributes.findIndex(a => a.value === 'initial-state') !== -1
40+
script = scripts.find(script =>
41+
script.attributes.some(({ value }) => value === 'initial-state')
4242
)
4343

44-
if (resourceScriptNew.length > 0) {
44+
if (script !== undefined) {
4545
// found data in the new embed style
4646
const data = JSON.parse(
47-
Buffer.from(
48-
decodeURIComponent(resourceScriptNew[0].children[0].content),
49-
'base64'
50-
)
47+
Buffer.from(decodeURIComponent(script.children[0].content), 'base64')
5148
).data.entity
5249
// they removed/renamed some things, which for backwards compatibility we need to add back
5350
data.external_urls = {
5451
spotify: 'https://open.spotify.com/track/' + data.uri
5552
}
5653
data.release_date = data.releaseDate.isoString
5754
data.audio = data.audioPreview.url
58-
return data
59-
}
60-
61-
const hydrateScript = scripts.filter(
62-
e => e.children[0] && /%22data%22%|"data":/.test(e.children[0].content)
63-
)
64-
65-
if (hydrateScript.length > 0) {
66-
// found hydration data
67-
// parsing via looking for { to be a little bit resistant to code changes
68-
const scriptContent = hydrateScript[0].children[0].content.includes(
69-
'%22data%22%'
70-
)
71-
? decodeURIComponent(hydrateScript[0].children[0].content)
72-
: hydrateScript[0].children[0].content
73-
return normalizeData(
74-
JSON.parse(
75-
'{' +
76-
scriptContent
77-
.split('{')
78-
.slice(1)
79-
.join('{')
80-
.trim()
81-
)
82-
)
55+
return normalizeData({ data })
8356
}
8457

8558
throw new Error(

0 commit comments

Comments
 (0)