builtin_array.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  1. package goja
  2. import (
  3. "math"
  4. "sort"
  5. "sync"
  6. )
  7. func (r *Runtime) newArray(prototype *Object) (a *arrayObject) {
  8. v := &Object{runtime: r}
  9. a = &arrayObject{}
  10. a.class = classArray
  11. a.val = v
  12. a.extensible = true
  13. v.self = a
  14. a.prototype = prototype
  15. a.init()
  16. return
  17. }
  18. func (r *Runtime) newArrayObject() *arrayObject {
  19. return r.newArray(r.getArrayPrototype())
  20. }
  21. func setArrayValues(a *arrayObject, values []Value) *arrayObject {
  22. a.values = values
  23. a.length = uint32(len(values))
  24. a.objCount = len(values)
  25. return a
  26. }
  27. func setArrayLength(a *arrayObject, l int64) *arrayObject {
  28. a.setOwnStr("length", intToValue(l), true)
  29. return a
  30. }
  31. func arraySpeciesCreate(obj *Object, size int64) *Object {
  32. if isArray(obj) {
  33. v := obj.self.getStr("constructor", nil)
  34. if constructObj, ok := v.(*Object); ok {
  35. v = constructObj.self.getSym(SymSpecies, nil)
  36. if v == _null {
  37. v = nil
  38. }
  39. }
  40. if v != nil && v != _undefined {
  41. constructObj, _ := v.(*Object)
  42. if constructObj != nil {
  43. if constructor := constructObj.self.assertConstructor(); constructor != nil {
  44. return constructor([]Value{intToValue(size)}, constructObj)
  45. }
  46. }
  47. panic(obj.runtime.NewTypeError("Species is not a constructor"))
  48. }
  49. }
  50. return obj.runtime.newArrayLength(size)
  51. }
  52. func max(a, b int64) int64 {
  53. if a > b {
  54. return a
  55. }
  56. return b
  57. }
  58. func min(a, b int64) int64 {
  59. if a < b {
  60. return a
  61. }
  62. return b
  63. }
  64. func relToIdx(rel, l int64) int64 {
  65. if rel >= 0 {
  66. return min(rel, l)
  67. }
  68. return max(l+rel, 0)
  69. }
  70. func (r *Runtime) newArrayValues(values []Value) *Object {
  71. return setArrayValues(r.newArrayObject(), values).val
  72. }
  73. func (r *Runtime) newArrayLength(l int64) *Object {
  74. return setArrayLength(r.newArrayObject(), l).val
  75. }
  76. func (r *Runtime) builtin_newArray(args []Value, proto *Object) *Object {
  77. l := len(args)
  78. if l == 1 {
  79. if al, ok := args[0].(valueInt); ok {
  80. return setArrayLength(r.newArray(proto), int64(al)).val
  81. } else if f, ok := args[0].(valueFloat); ok {
  82. al := int64(f)
  83. if float64(al) == float64(f) {
  84. return r.newArrayLength(al)
  85. } else {
  86. panic(r.newError(r.getRangeError(), "Invalid array length"))
  87. }
  88. }
  89. return setArrayValues(r.newArray(proto), []Value{args[0]}).val
  90. } else {
  91. argsCopy := make([]Value, l)
  92. copy(argsCopy, args)
  93. return setArrayValues(r.newArray(proto), argsCopy).val
  94. }
  95. }
  96. func (r *Runtime) generic_push(obj *Object, call FunctionCall) Value {
  97. l := toLength(obj.self.getStr("length", nil))
  98. nl := l + int64(len(call.Arguments))
  99. if nl >= maxInt {
  100. r.typeErrorResult(true, "Invalid array length")
  101. panic("unreachable")
  102. }
  103. for i, arg := range call.Arguments {
  104. obj.self.setOwnIdx(valueInt(l+int64(i)), arg, true)
  105. }
  106. n := valueInt(nl)
  107. obj.self.setOwnStr("length", n, true)
  108. return n
  109. }
  110. func (r *Runtime) arrayproto_push(call FunctionCall) Value {
  111. obj := call.This.ToObject(r)
  112. return r.generic_push(obj, call)
  113. }
  114. func (r *Runtime) arrayproto_pop_generic(obj *Object) Value {
  115. l := toLength(obj.self.getStr("length", nil))
  116. if l == 0 {
  117. obj.self.setOwnStr("length", intToValue(0), true)
  118. return _undefined
  119. }
  120. idx := valueInt(l - 1)
  121. val := obj.self.getIdx(idx, nil)
  122. obj.self.deleteIdx(idx, true)
  123. obj.self.setOwnStr("length", idx, true)
  124. return val
  125. }
  126. func (r *Runtime) arrayproto_pop(call FunctionCall) Value {
  127. obj := call.This.ToObject(r)
  128. if a, ok := obj.self.(*arrayObject); ok {
  129. l := a.length
  130. var val Value
  131. if l > 0 {
  132. l--
  133. if l < uint32(len(a.values)) {
  134. val = a.values[l]
  135. }
  136. if val == nil {
  137. // optimisation bail-out
  138. return r.arrayproto_pop_generic(obj)
  139. }
  140. if _, ok := val.(*valueProperty); ok {
  141. // optimisation bail-out
  142. return r.arrayproto_pop_generic(obj)
  143. }
  144. //a._setLengthInt(l, false)
  145. a.values[l] = nil
  146. a.values = a.values[:l]
  147. } else {
  148. val = _undefined
  149. }
  150. if a.lengthProp.writable {
  151. a.length = l
  152. } else {
  153. a.setLength(0, true) // will throw
  154. }
  155. return val
  156. } else {
  157. return r.arrayproto_pop_generic(obj)
  158. }
  159. }
  160. func (r *Runtime) arrayproto_join(call FunctionCall) Value {
  161. o := call.This.ToObject(r)
  162. l := int(toLength(o.self.getStr("length", nil)))
  163. var sep String
  164. if s := call.Argument(0); s != _undefined {
  165. sep = s.toString()
  166. } else {
  167. sep = asciiString(",")
  168. }
  169. if l == 0 {
  170. return stringEmpty
  171. }
  172. var buf StringBuilder
  173. element0 := o.self.getIdx(valueInt(0), nil)
  174. if element0 != nil && element0 != _undefined && element0 != _null {
  175. buf.WriteString(element0.toString())
  176. }
  177. for i := 1; i < l; i++ {
  178. buf.WriteString(sep)
  179. element := o.self.getIdx(valueInt(int64(i)), nil)
  180. if element != nil && element != _undefined && element != _null {
  181. buf.WriteString(element.toString())
  182. }
  183. }
  184. return buf.String()
  185. }
  186. func (r *Runtime) arrayproto_toString(call FunctionCall) Value {
  187. array := call.This.ToObject(r)
  188. var toString func() Value
  189. switch a := array.self.(type) {
  190. case *objectGoSliceReflect:
  191. toString = a.toString
  192. case *objectGoArrayReflect:
  193. toString = a.toString
  194. }
  195. if toString != nil {
  196. return toString()
  197. }
  198. f := array.self.getStr("join", nil)
  199. if fObj, ok := f.(*Object); ok {
  200. if fcall, ok := fObj.self.assertCallable(); ok {
  201. return fcall(FunctionCall{
  202. This: array,
  203. })
  204. }
  205. }
  206. return r.objectproto_toString(FunctionCall{
  207. This: array,
  208. })
  209. }
  210. func (r *Runtime) writeItemLocaleString(item Value, buf *StringBuilder) {
  211. if item != nil && item != _undefined && item != _null {
  212. if f, ok := r.getVStr(item, "toLocaleString").(*Object); ok {
  213. if c, ok := f.self.assertCallable(); ok {
  214. strVal := c(FunctionCall{
  215. This: item,
  216. })
  217. buf.WriteString(strVal.toString())
  218. return
  219. }
  220. }
  221. r.typeErrorResult(true, "Property 'toLocaleString' of object %s is not a function", item)
  222. }
  223. }
  224. func (r *Runtime) arrayproto_toLocaleString(call FunctionCall) Value {
  225. array := call.This.ToObject(r)
  226. var buf StringBuilder
  227. if a := r.checkStdArrayObj(array); a != nil {
  228. for i, item := range a.values {
  229. if i > 0 {
  230. buf.WriteRune(',')
  231. }
  232. r.writeItemLocaleString(item, &buf)
  233. }
  234. } else {
  235. length := toLength(array.self.getStr("length", nil))
  236. for i := int64(0); i < length; i++ {
  237. if i > 0 {
  238. buf.WriteRune(',')
  239. }
  240. item := array.self.getIdx(valueInt(i), nil)
  241. r.writeItemLocaleString(item, &buf)
  242. }
  243. }
  244. return buf.String()
  245. }
  246. func isConcatSpreadable(obj *Object) bool {
  247. spreadable := obj.self.getSym(SymIsConcatSpreadable, nil)
  248. if spreadable != nil && spreadable != _undefined {
  249. return spreadable.ToBoolean()
  250. }
  251. return isArray(obj)
  252. }
  253. func (r *Runtime) arrayproto_concat_append(a *Object, item Value) {
  254. aLength := toLength(a.self.getStr("length", nil))
  255. if obj, ok := item.(*Object); ok && isConcatSpreadable(obj) {
  256. length := toLength(obj.self.getStr("length", nil))
  257. if aLength+length >= maxInt {
  258. panic(r.NewTypeError("Invalid array length"))
  259. }
  260. for i := int64(0); i < length; i++ {
  261. v := obj.self.getIdx(valueInt(i), nil)
  262. if v != nil {
  263. createDataPropertyOrThrow(a, intToValue(aLength), v)
  264. }
  265. aLength++
  266. }
  267. } else {
  268. createDataPropertyOrThrow(a, intToValue(aLength), item)
  269. aLength++
  270. }
  271. a.self.setOwnStr("length", intToValue(aLength), true)
  272. }
  273. func (r *Runtime) arrayproto_concat(call FunctionCall) Value {
  274. obj := call.This.ToObject(r)
  275. a := arraySpeciesCreate(obj, 0)
  276. r.arrayproto_concat_append(a, call.This.ToObject(r))
  277. for _, item := range call.Arguments {
  278. r.arrayproto_concat_append(a, item)
  279. }
  280. return a
  281. }
  282. func (r *Runtime) arrayproto_slice(call FunctionCall) Value {
  283. o := call.This.ToObject(r)
  284. length := toLength(o.self.getStr("length", nil))
  285. start := relToIdx(call.Argument(0).ToInteger(), length)
  286. var end int64
  287. if endArg := call.Argument(1); endArg != _undefined {
  288. end = endArg.ToInteger()
  289. } else {
  290. end = length
  291. }
  292. end = relToIdx(end, length)
  293. count := end - start
  294. if count < 0 {
  295. count = 0
  296. }
  297. a := arraySpeciesCreate(o, count)
  298. if src := r.checkStdArrayObj(o); src != nil {
  299. if dst := r.checkStdArrayObjWithProto(a); dst != nil {
  300. values := make([]Value, count)
  301. copy(values, src.values[start:])
  302. setArrayValues(dst, values)
  303. return a
  304. }
  305. }
  306. n := int64(0)
  307. for start < end {
  308. p := o.self.getIdx(valueInt(start), nil)
  309. if p != nil {
  310. createDataPropertyOrThrow(a, valueInt(n), p)
  311. }
  312. start++
  313. n++
  314. }
  315. return a
  316. }
  317. func (r *Runtime) arrayproto_sort(call FunctionCall) Value {
  318. o := call.This.ToObject(r)
  319. var compareFn func(FunctionCall) Value
  320. arg := call.Argument(0)
  321. if arg != _undefined {
  322. if arg, ok := call.Argument(0).(*Object); ok {
  323. compareFn, _ = arg.self.assertCallable()
  324. }
  325. if compareFn == nil {
  326. panic(r.NewTypeError("The comparison function must be either a function or undefined"))
  327. }
  328. }
  329. var s sortable
  330. if r.checkStdArrayObj(o) != nil {
  331. s = o.self
  332. } else if _, ok := o.self.(reflectValueWrapper); ok {
  333. s = o.self
  334. }
  335. if s != nil {
  336. ctx := arraySortCtx{
  337. obj: s,
  338. compare: compareFn,
  339. }
  340. sort.Stable(&ctx)
  341. } else {
  342. length := toLength(o.self.getStr("length", nil))
  343. a := make([]Value, 0, length)
  344. for i := int64(0); i < length; i++ {
  345. idx := valueInt(i)
  346. if o.self.hasPropertyIdx(idx) {
  347. a = append(a, nilSafe(o.self.getIdx(idx, nil)))
  348. }
  349. }
  350. ar := r.newArrayValues(a)
  351. ctx := arraySortCtx{
  352. obj: ar.self,
  353. compare: compareFn,
  354. }
  355. sort.Stable(&ctx)
  356. for i := 0; i < len(a); i++ {
  357. o.self.setOwnIdx(valueInt(i), a[i], true)
  358. }
  359. for i := int64(len(a)); i < length; i++ {
  360. o.self.deleteIdx(valueInt(i), true)
  361. }
  362. }
  363. return o
  364. }
  365. func (r *Runtime) arrayproto_splice(call FunctionCall) Value {
  366. o := call.This.ToObject(r)
  367. length := toLength(o.self.getStr("length", nil))
  368. actualStart := relToIdx(call.Argument(0).ToInteger(), length)
  369. var actualDeleteCount int64
  370. switch len(call.Arguments) {
  371. case 0:
  372. case 1:
  373. actualDeleteCount = length - actualStart
  374. default:
  375. actualDeleteCount = min(max(call.Argument(1).ToInteger(), 0), length-actualStart)
  376. }
  377. itemCount := max(int64(len(call.Arguments)-2), 0)
  378. newLength := length - actualDeleteCount + itemCount
  379. if newLength >= maxInt {
  380. panic(r.NewTypeError("Invalid array length"))
  381. }
  382. a := arraySpeciesCreate(o, actualDeleteCount)
  383. if src := r.checkStdArrayObj(o); src != nil {
  384. if dst := r.checkStdArrayObjWithProto(a); dst != nil {
  385. values := make([]Value, actualDeleteCount)
  386. copy(values, src.values[actualStart:])
  387. setArrayValues(dst, values)
  388. } else {
  389. for k := int64(0); k < actualDeleteCount; k++ {
  390. createDataPropertyOrThrow(a, intToValue(k), src.values[k+actualStart])
  391. }
  392. a.self.setOwnStr("length", intToValue(actualDeleteCount), true)
  393. }
  394. var values []Value
  395. if itemCount < actualDeleteCount {
  396. values = src.values
  397. copy(values[actualStart+itemCount:], values[actualStart+actualDeleteCount:])
  398. tail := values[newLength:]
  399. for k := range tail {
  400. tail[k] = nil
  401. }
  402. values = values[:newLength]
  403. } else if itemCount > actualDeleteCount {
  404. if int64(cap(src.values)) >= newLength {
  405. values = src.values[:newLength]
  406. copy(values[actualStart+itemCount:], values[actualStart+actualDeleteCount:length])
  407. } else {
  408. values = make([]Value, newLength)
  409. copy(values, src.values[:actualStart])
  410. copy(values[actualStart+itemCount:], src.values[actualStart+actualDeleteCount:])
  411. }
  412. } else {
  413. values = src.values
  414. }
  415. if itemCount > 0 {
  416. copy(values[actualStart:], call.Arguments[2:])
  417. }
  418. src.values = values
  419. src.objCount = len(values)
  420. } else {
  421. for k := int64(0); k < actualDeleteCount; k++ {
  422. from := valueInt(k + actualStart)
  423. if o.self.hasPropertyIdx(from) {
  424. createDataPropertyOrThrow(a, valueInt(k), nilSafe(o.self.getIdx(from, nil)))
  425. }
  426. }
  427. if itemCount < actualDeleteCount {
  428. for k := actualStart; k < length-actualDeleteCount; k++ {
  429. from := valueInt(k + actualDeleteCount)
  430. to := valueInt(k + itemCount)
  431. if o.self.hasPropertyIdx(from) {
  432. o.self.setOwnIdx(to, nilSafe(o.self.getIdx(from, nil)), true)
  433. } else {
  434. o.self.deleteIdx(to, true)
  435. }
  436. }
  437. for k := length; k > length-actualDeleteCount+itemCount; k-- {
  438. o.self.deleteIdx(valueInt(k-1), true)
  439. }
  440. } else if itemCount > actualDeleteCount {
  441. for k := length - actualDeleteCount; k > actualStart; k-- {
  442. from := valueInt(k + actualDeleteCount - 1)
  443. to := valueInt(k + itemCount - 1)
  444. if o.self.hasPropertyIdx(from) {
  445. o.self.setOwnIdx(to, nilSafe(o.self.getIdx(from, nil)), true)
  446. } else {
  447. o.self.deleteIdx(to, true)
  448. }
  449. }
  450. }
  451. if itemCount > 0 {
  452. for i, item := range call.Arguments[2:] {
  453. o.self.setOwnIdx(valueInt(actualStart+int64(i)), item, true)
  454. }
  455. }
  456. }
  457. o.self.setOwnStr("length", intToValue(newLength), true)
  458. return a
  459. }
  460. func (r *Runtime) arrayproto_unshift(call FunctionCall) Value {
  461. o := call.This.ToObject(r)
  462. length := toLength(o.self.getStr("length", nil))
  463. argCount := int64(len(call.Arguments))
  464. newLen := intToValue(length + argCount)
  465. if argCount > 0 {
  466. newSize := length + argCount
  467. if newSize >= maxInt {
  468. panic(r.NewTypeError("Invalid array length"))
  469. }
  470. if arr := r.checkStdArrayObjWithProto(o); arr != nil && newSize < math.MaxUint32 {
  471. if int64(cap(arr.values)) >= newSize {
  472. arr.values = arr.values[:newSize]
  473. copy(arr.values[argCount:], arr.values[:length])
  474. } else {
  475. values := make([]Value, newSize)
  476. copy(values[argCount:], arr.values)
  477. arr.values = values
  478. }
  479. copy(arr.values, call.Arguments)
  480. arr.objCount = int(arr.length)
  481. } else {
  482. for k := length - 1; k >= 0; k-- {
  483. from := valueInt(k)
  484. to := valueInt(k + argCount)
  485. if o.self.hasPropertyIdx(from) {
  486. o.self.setOwnIdx(to, nilSafe(o.self.getIdx(from, nil)), true)
  487. } else {
  488. o.self.deleteIdx(to, true)
  489. }
  490. }
  491. for k, arg := range call.Arguments {
  492. o.self.setOwnIdx(valueInt(int64(k)), arg, true)
  493. }
  494. }
  495. }
  496. o.self.setOwnStr("length", newLen, true)
  497. return newLen
  498. }
  499. func (r *Runtime) arrayproto_at(call FunctionCall) Value {
  500. o := call.This.ToObject(r)
  501. idx := call.Argument(0).ToInteger()
  502. length := toLength(o.self.getStr("length", nil))
  503. if idx < 0 {
  504. idx = length + idx
  505. }
  506. if idx >= length || idx < 0 {
  507. return _undefined
  508. }
  509. i := valueInt(idx)
  510. if o.self.hasPropertyIdx(i) {
  511. return o.self.getIdx(i, nil)
  512. }
  513. return _undefined
  514. }
  515. func (r *Runtime) arrayproto_indexOf(call FunctionCall) Value {
  516. o := call.This.ToObject(r)
  517. length := toLength(o.self.getStr("length", nil))
  518. if length == 0 {
  519. return intToValue(-1)
  520. }
  521. n := call.Argument(1).ToInteger()
  522. if n >= length {
  523. return intToValue(-1)
  524. }
  525. if n < 0 {
  526. n = max(length+n, 0)
  527. }
  528. searchElement := call.Argument(0)
  529. if arr := r.checkStdArrayObj(o); arr != nil {
  530. for i, val := range arr.values[n:] {
  531. if searchElement.StrictEquals(val) {
  532. return intToValue(n + int64(i))
  533. }
  534. }
  535. return intToValue(-1)
  536. }
  537. for ; n < length; n++ {
  538. idx := valueInt(n)
  539. if o.self.hasPropertyIdx(idx) {
  540. if val := o.self.getIdx(idx, nil); val != nil {
  541. if searchElement.StrictEquals(val) {
  542. return idx
  543. }
  544. }
  545. }
  546. }
  547. return intToValue(-1)
  548. }
  549. func (r *Runtime) arrayproto_includes(call FunctionCall) Value {
  550. o := call.This.ToObject(r)
  551. length := toLength(o.self.getStr("length", nil))
  552. if length == 0 {
  553. return valueFalse
  554. }
  555. n := call.Argument(1).ToInteger()
  556. if n >= length {
  557. return valueFalse
  558. }
  559. if n < 0 {
  560. n = max(length+n, 0)
  561. }
  562. searchElement := call.Argument(0)
  563. if searchElement == _negativeZero {
  564. searchElement = _positiveZero
  565. }
  566. if arr := r.checkStdArrayObj(o); arr != nil {
  567. for _, val := range arr.values[n:] {
  568. if searchElement.SameAs(val) {
  569. return valueTrue
  570. }
  571. }
  572. return valueFalse
  573. }
  574. for ; n < length; n++ {
  575. idx := valueInt(n)
  576. val := nilSafe(o.self.getIdx(idx, nil))
  577. if searchElement.SameAs(val) {
  578. return valueTrue
  579. }
  580. }
  581. return valueFalse
  582. }
  583. func (r *Runtime) arrayproto_lastIndexOf(call FunctionCall) Value {
  584. o := call.This.ToObject(r)
  585. length := toLength(o.self.getStr("length", nil))
  586. if length == 0 {
  587. return intToValue(-1)
  588. }
  589. var fromIndex int64
  590. if len(call.Arguments) < 2 {
  591. fromIndex = length - 1
  592. } else {
  593. fromIndex = call.Argument(1).ToInteger()
  594. if fromIndex >= 0 {
  595. fromIndex = min(fromIndex, length-1)
  596. } else {
  597. fromIndex += length
  598. }
  599. }
  600. searchElement := call.Argument(0)
  601. if arr := r.checkStdArrayObj(o); arr != nil {
  602. vals := arr.values
  603. for k := fromIndex; k >= 0; k-- {
  604. if v := vals[k]; v != nil && searchElement.StrictEquals(v) {
  605. return intToValue(k)
  606. }
  607. }
  608. return intToValue(-1)
  609. }
  610. for k := fromIndex; k >= 0; k-- {
  611. idx := valueInt(k)
  612. if o.self.hasPropertyIdx(idx) {
  613. if val := o.self.getIdx(idx, nil); val != nil {
  614. if searchElement.StrictEquals(val) {
  615. return idx
  616. }
  617. }
  618. }
  619. }
  620. return intToValue(-1)
  621. }
  622. func (r *Runtime) arrayproto_every(call FunctionCall) Value {
  623. o := call.This.ToObject(r)
  624. length := toLength(o.self.getStr("length", nil))
  625. callbackFn := r.toCallable(call.Argument(0))
  626. fc := FunctionCall{
  627. This: call.Argument(1),
  628. Arguments: []Value{nil, nil, o},
  629. }
  630. for k := int64(0); k < length; k++ {
  631. idx := valueInt(k)
  632. if val := o.self.getIdx(idx, nil); val != nil {
  633. fc.Arguments[0] = val
  634. fc.Arguments[1] = idx
  635. if !callbackFn(fc).ToBoolean() {
  636. return valueFalse
  637. }
  638. }
  639. }
  640. return valueTrue
  641. }
  642. func (r *Runtime) arrayproto_some(call FunctionCall) Value {
  643. o := call.This.ToObject(r)
  644. length := toLength(o.self.getStr("length", nil))
  645. callbackFn := r.toCallable(call.Argument(0))
  646. fc := FunctionCall{
  647. This: call.Argument(1),
  648. Arguments: []Value{nil, nil, o},
  649. }
  650. for k := int64(0); k < length; k++ {
  651. idx := valueInt(k)
  652. if val := o.self.getIdx(idx, nil); val != nil {
  653. fc.Arguments[0] = val
  654. fc.Arguments[1] = idx
  655. if callbackFn(fc).ToBoolean() {
  656. return valueTrue
  657. }
  658. }
  659. }
  660. return valueFalse
  661. }
  662. func (r *Runtime) arrayproto_forEach(call FunctionCall) Value {
  663. o := call.This.ToObject(r)
  664. length := toLength(o.self.getStr("length", nil))
  665. callbackFn := r.toCallable(call.Argument(0))
  666. fc := FunctionCall{
  667. This: call.Argument(1),
  668. Arguments: []Value{nil, nil, o},
  669. }
  670. for k := int64(0); k < length; k++ {
  671. idx := valueInt(k)
  672. if val := o.self.getIdx(idx, nil); val != nil {
  673. fc.Arguments[0] = val
  674. fc.Arguments[1] = idx
  675. callbackFn(fc)
  676. }
  677. }
  678. return _undefined
  679. }
  680. func (r *Runtime) arrayproto_map(call FunctionCall) Value {
  681. o := call.This.ToObject(r)
  682. length := toLength(o.self.getStr("length", nil))
  683. callbackFn := r.toCallable(call.Argument(0))
  684. fc := FunctionCall{
  685. This: call.Argument(1),
  686. Arguments: []Value{nil, nil, o},
  687. }
  688. a := arraySpeciesCreate(o, length)
  689. if _, stdSrc := o.self.(*arrayObject); stdSrc {
  690. if arr, ok := a.self.(*arrayObject); ok {
  691. values := make([]Value, length)
  692. for k := int64(0); k < length; k++ {
  693. idx := valueInt(k)
  694. if val := o.self.getIdx(idx, nil); val != nil {
  695. fc.Arguments[0] = val
  696. fc.Arguments[1] = idx
  697. values[k] = callbackFn(fc)
  698. }
  699. }
  700. setArrayValues(arr, values)
  701. return a
  702. }
  703. }
  704. for k := int64(0); k < length; k++ {
  705. idx := valueInt(k)
  706. if val := o.self.getIdx(idx, nil); val != nil {
  707. fc.Arguments[0] = val
  708. fc.Arguments[1] = idx
  709. createDataPropertyOrThrow(a, idx, callbackFn(fc))
  710. }
  711. }
  712. return a
  713. }
  714. func (r *Runtime) arrayproto_filter(call FunctionCall) Value {
  715. o := call.This.ToObject(r)
  716. length := toLength(o.self.getStr("length", nil))
  717. callbackFn := call.Argument(0).ToObject(r)
  718. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  719. a := arraySpeciesCreate(o, 0)
  720. fc := FunctionCall{
  721. This: call.Argument(1),
  722. Arguments: []Value{nil, nil, o},
  723. }
  724. if _, stdSrc := o.self.(*arrayObject); stdSrc {
  725. if arr := r.checkStdArrayObj(a); arr != nil {
  726. var values []Value
  727. for k := int64(0); k < length; k++ {
  728. idx := valueInt(k)
  729. if val := o.self.getIdx(idx, nil); val != nil {
  730. fc.Arguments[0] = val
  731. fc.Arguments[1] = idx
  732. if callbackFn(fc).ToBoolean() {
  733. values = append(values, val)
  734. }
  735. }
  736. }
  737. setArrayValues(arr, values)
  738. return a
  739. }
  740. }
  741. to := int64(0)
  742. for k := int64(0); k < length; k++ {
  743. idx := valueInt(k)
  744. if val := o.self.getIdx(idx, nil); val != nil {
  745. fc.Arguments[0] = val
  746. fc.Arguments[1] = idx
  747. if callbackFn(fc).ToBoolean() {
  748. createDataPropertyOrThrow(a, intToValue(to), val)
  749. to++
  750. }
  751. }
  752. }
  753. return a
  754. } else {
  755. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  756. }
  757. panic("unreachable")
  758. }
  759. func (r *Runtime) arrayproto_reduce(call FunctionCall) Value {
  760. o := call.This.ToObject(r)
  761. length := toLength(o.self.getStr("length", nil))
  762. callbackFn := call.Argument(0).ToObject(r)
  763. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  764. fc := FunctionCall{
  765. This: _undefined,
  766. Arguments: []Value{nil, nil, nil, o},
  767. }
  768. var k int64
  769. if len(call.Arguments) >= 2 {
  770. fc.Arguments[0] = call.Argument(1)
  771. } else {
  772. for ; k < length; k++ {
  773. idx := valueInt(k)
  774. if val := o.self.getIdx(idx, nil); val != nil {
  775. fc.Arguments[0] = val
  776. break
  777. }
  778. }
  779. if fc.Arguments[0] == nil {
  780. r.typeErrorResult(true, "No initial value")
  781. panic("unreachable")
  782. }
  783. k++
  784. }
  785. for ; k < length; k++ {
  786. idx := valueInt(k)
  787. if val := o.self.getIdx(idx, nil); val != nil {
  788. fc.Arguments[1] = val
  789. fc.Arguments[2] = idx
  790. fc.Arguments[0] = callbackFn(fc)
  791. }
  792. }
  793. return fc.Arguments[0]
  794. } else {
  795. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  796. }
  797. panic("unreachable")
  798. }
  799. func (r *Runtime) arrayproto_reduceRight(call FunctionCall) Value {
  800. o := call.This.ToObject(r)
  801. length := toLength(o.self.getStr("length", nil))
  802. callbackFn := call.Argument(0).ToObject(r)
  803. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  804. fc := FunctionCall{
  805. This: _undefined,
  806. Arguments: []Value{nil, nil, nil, o},
  807. }
  808. k := length - 1
  809. if len(call.Arguments) >= 2 {
  810. fc.Arguments[0] = call.Argument(1)
  811. } else {
  812. for ; k >= 0; k-- {
  813. idx := valueInt(k)
  814. if val := o.self.getIdx(idx, nil); val != nil {
  815. fc.Arguments[0] = val
  816. break
  817. }
  818. }
  819. if fc.Arguments[0] == nil {
  820. r.typeErrorResult(true, "No initial value")
  821. panic("unreachable")
  822. }
  823. k--
  824. }
  825. for ; k >= 0; k-- {
  826. idx := valueInt(k)
  827. if val := o.self.getIdx(idx, nil); val != nil {
  828. fc.Arguments[1] = val
  829. fc.Arguments[2] = idx
  830. fc.Arguments[0] = callbackFn(fc)
  831. }
  832. }
  833. return fc.Arguments[0]
  834. } else {
  835. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  836. }
  837. panic("unreachable")
  838. }
  839. func arrayproto_reverse_generic_step(o *Object, lower, upper int64) {
  840. lowerP := valueInt(lower)
  841. upperP := valueInt(upper)
  842. var lowerValue, upperValue Value
  843. lowerExists := o.self.hasPropertyIdx(lowerP)
  844. if lowerExists {
  845. lowerValue = nilSafe(o.self.getIdx(lowerP, nil))
  846. }
  847. upperExists := o.self.hasPropertyIdx(upperP)
  848. if upperExists {
  849. upperValue = nilSafe(o.self.getIdx(upperP, nil))
  850. }
  851. if lowerExists && upperExists {
  852. o.self.setOwnIdx(lowerP, upperValue, true)
  853. o.self.setOwnIdx(upperP, lowerValue, true)
  854. } else if !lowerExists && upperExists {
  855. o.self.setOwnIdx(lowerP, upperValue, true)
  856. o.self.deleteIdx(upperP, true)
  857. } else if lowerExists && !upperExists {
  858. o.self.deleteIdx(lowerP, true)
  859. o.self.setOwnIdx(upperP, lowerValue, true)
  860. }
  861. }
  862. func (r *Runtime) arrayproto_reverse_generic(o *Object, start int64) {
  863. l := toLength(o.self.getStr("length", nil))
  864. middle := l / 2
  865. for lower := start; lower != middle; lower++ {
  866. arrayproto_reverse_generic_step(o, lower, l-lower-1)
  867. }
  868. }
  869. func (r *Runtime) arrayproto_reverse(call FunctionCall) Value {
  870. o := call.This.ToObject(r)
  871. if a := r.checkStdArrayObj(o); a != nil {
  872. l := len(a.values)
  873. middle := l / 2
  874. for lower := 0; lower != middle; lower++ {
  875. upper := l - lower - 1
  876. a.values[lower], a.values[upper] = a.values[upper], a.values[lower]
  877. }
  878. //TODO: go arrays
  879. } else {
  880. r.arrayproto_reverse_generic(o, 0)
  881. }
  882. return o
  883. }
  884. func (r *Runtime) arrayproto_shift(call FunctionCall) Value {
  885. o := call.This.ToObject(r)
  886. if a := r.checkStdArrayObjWithProto(o); a != nil {
  887. if len(a.values) == 0 {
  888. if !a.lengthProp.writable {
  889. a.setLength(0, true) // will throw
  890. }
  891. return _undefined
  892. }
  893. first := a.values[0]
  894. copy(a.values, a.values[1:])
  895. a.values[len(a.values)-1] = nil
  896. a.values = a.values[:len(a.values)-1]
  897. a.length--
  898. return first
  899. }
  900. length := toLength(o.self.getStr("length", nil))
  901. if length == 0 {
  902. o.self.setOwnStr("length", intToValue(0), true)
  903. return _undefined
  904. }
  905. first := o.self.getIdx(valueInt(0), nil)
  906. for i := int64(1); i < length; i++ {
  907. idxFrom := valueInt(i)
  908. idxTo := valueInt(i - 1)
  909. if o.self.hasPropertyIdx(idxFrom) {
  910. o.self.setOwnIdx(idxTo, nilSafe(o.self.getIdx(idxFrom, nil)), true)
  911. } else {
  912. o.self.deleteIdx(idxTo, true)
  913. }
  914. }
  915. lv := valueInt(length - 1)
  916. o.self.deleteIdx(lv, true)
  917. o.self.setOwnStr("length", lv, true)
  918. return first
  919. }
  920. func (r *Runtime) arrayproto_values(call FunctionCall) Value {
  921. return r.createArrayIterator(call.This.ToObject(r), iterationKindValue)
  922. }
  923. func (r *Runtime) arrayproto_keys(call FunctionCall) Value {
  924. return r.createArrayIterator(call.This.ToObject(r), iterationKindKey)
  925. }
  926. func (r *Runtime) arrayproto_copyWithin(call FunctionCall) Value {
  927. o := call.This.ToObject(r)
  928. l := toLength(o.self.getStr("length", nil))
  929. var relEnd, dir int64
  930. to := relToIdx(call.Argument(0).ToInteger(), l)
  931. from := relToIdx(call.Argument(1).ToInteger(), l)
  932. if end := call.Argument(2); end != _undefined {
  933. relEnd = end.ToInteger()
  934. } else {
  935. relEnd = l
  936. }
  937. final := relToIdx(relEnd, l)
  938. count := min(final-from, l-to)
  939. if arr := r.checkStdArrayObj(o); arr != nil {
  940. if count > 0 {
  941. copy(arr.values[to:to+count], arr.values[from:from+count])
  942. }
  943. return o
  944. }
  945. if from < to && to < from+count {
  946. dir = -1
  947. from = from + count - 1
  948. to = to + count - 1
  949. } else {
  950. dir = 1
  951. }
  952. for count > 0 {
  953. if o.self.hasPropertyIdx(valueInt(from)) {
  954. o.self.setOwnIdx(valueInt(to), nilSafe(o.self.getIdx(valueInt(from), nil)), true)
  955. } else {
  956. o.self.deleteIdx(valueInt(to), true)
  957. }
  958. from += dir
  959. to += dir
  960. count--
  961. }
  962. return o
  963. }
  964. func (r *Runtime) arrayproto_entries(call FunctionCall) Value {
  965. return r.createArrayIterator(call.This.ToObject(r), iterationKindKeyValue)
  966. }
  967. func (r *Runtime) arrayproto_fill(call FunctionCall) Value {
  968. o := call.This.ToObject(r)
  969. l := toLength(o.self.getStr("length", nil))
  970. k := relToIdx(call.Argument(1).ToInteger(), l)
  971. var relEnd int64
  972. if endArg := call.Argument(2); endArg != _undefined {
  973. relEnd = endArg.ToInteger()
  974. } else {
  975. relEnd = l
  976. }
  977. final := relToIdx(relEnd, l)
  978. value := call.Argument(0)
  979. if arr := r.checkStdArrayObj(o); arr != nil {
  980. for ; k < final; k++ {
  981. arr.values[k] = value
  982. }
  983. } else {
  984. for ; k < final; k++ {
  985. o.self.setOwnIdx(valueInt(k), value, true)
  986. }
  987. }
  988. return o
  989. }
  990. func (r *Runtime) arrayproto_find(call FunctionCall) Value {
  991. o := call.This.ToObject(r)
  992. l := toLength(o.self.getStr("length", nil))
  993. predicate := r.toCallable(call.Argument(0))
  994. fc := FunctionCall{
  995. This: call.Argument(1),
  996. Arguments: []Value{nil, nil, o},
  997. }
  998. for k := int64(0); k < l; k++ {
  999. idx := valueInt(k)
  1000. kValue := o.self.getIdx(idx, nil)
  1001. fc.Arguments[0], fc.Arguments[1] = kValue, idx
  1002. if predicate(fc).ToBoolean() {
  1003. return kValue
  1004. }
  1005. }
  1006. return _undefined
  1007. }
  1008. func (r *Runtime) arrayproto_findIndex(call FunctionCall) Value {
  1009. o := call.This.ToObject(r)
  1010. l := toLength(o.self.getStr("length", nil))
  1011. predicate := r.toCallable(call.Argument(0))
  1012. fc := FunctionCall{
  1013. This: call.Argument(1),
  1014. Arguments: []Value{nil, nil, o},
  1015. }
  1016. for k := int64(0); k < l; k++ {
  1017. idx := valueInt(k)
  1018. kValue := o.self.getIdx(idx, nil)
  1019. fc.Arguments[0], fc.Arguments[1] = kValue, idx
  1020. if predicate(fc).ToBoolean() {
  1021. return idx
  1022. }
  1023. }
  1024. return intToValue(-1)
  1025. }
  1026. func (r *Runtime) arrayproto_findLast(call FunctionCall) Value {
  1027. o := call.This.ToObject(r)
  1028. l := toLength(o.self.getStr("length", nil))
  1029. predicate := r.toCallable(call.Argument(0))
  1030. fc := FunctionCall{
  1031. This: call.Argument(1),
  1032. Arguments: []Value{nil, nil, o},
  1033. }
  1034. for k := int64(l - 1); k >= 0; k-- {
  1035. idx := valueInt(k)
  1036. kValue := o.self.getIdx(idx, nil)
  1037. fc.Arguments[0], fc.Arguments[1] = kValue, idx
  1038. if predicate(fc).ToBoolean() {
  1039. return kValue
  1040. }
  1041. }
  1042. return _undefined
  1043. }
  1044. func (r *Runtime) arrayproto_findLastIndex(call FunctionCall) Value {
  1045. o := call.This.ToObject(r)
  1046. l := toLength(o.self.getStr("length", nil))
  1047. predicate := r.toCallable(call.Argument(0))
  1048. fc := FunctionCall{
  1049. This: call.Argument(1),
  1050. Arguments: []Value{nil, nil, o},
  1051. }
  1052. for k := int64(l - 1); k >= 0; k-- {
  1053. idx := valueInt(k)
  1054. kValue := o.self.getIdx(idx, nil)
  1055. fc.Arguments[0], fc.Arguments[1] = kValue, idx
  1056. if predicate(fc).ToBoolean() {
  1057. return idx
  1058. }
  1059. }
  1060. return intToValue(-1)
  1061. }
  1062. func (r *Runtime) arrayproto_flat(call FunctionCall) Value {
  1063. o := call.This.ToObject(r)
  1064. l := toLength(o.self.getStr("length", nil))
  1065. depthNum := int64(1)
  1066. if len(call.Arguments) > 0 {
  1067. depthNum = call.Argument(0).ToInteger()
  1068. }
  1069. a := arraySpeciesCreate(o, 0)
  1070. r.flattenIntoArray(a, o, l, 0, depthNum, nil, nil)
  1071. return a
  1072. }
  1073. func (r *Runtime) flattenIntoArray(target, source *Object, sourceLen, start, depth int64, mapperFunction func(FunctionCall) Value, thisArg Value) int64 {
  1074. targetIndex, sourceIndex := start, int64(0)
  1075. for sourceIndex < sourceLen {
  1076. p := intToValue(sourceIndex)
  1077. if source.hasProperty(p.toString()) {
  1078. element := nilSafe(source.get(p, source))
  1079. if mapperFunction != nil {
  1080. element = mapperFunction(FunctionCall{
  1081. This: thisArg,
  1082. Arguments: []Value{element, p, source},
  1083. })
  1084. }
  1085. var elementArray *Object
  1086. if depth > 0 {
  1087. if elementObj, ok := element.(*Object); ok && isArray(elementObj) {
  1088. elementArray = elementObj
  1089. }
  1090. }
  1091. if elementArray != nil {
  1092. elementLen := toLength(elementArray.self.getStr("length", nil))
  1093. targetIndex = r.flattenIntoArray(target, elementArray, elementLen, targetIndex, depth-1, nil, nil)
  1094. } else {
  1095. if targetIndex >= maxInt-1 {
  1096. panic(r.NewTypeError("Invalid array length"))
  1097. }
  1098. createDataPropertyOrThrow(target, intToValue(targetIndex), element)
  1099. targetIndex++
  1100. }
  1101. }
  1102. sourceIndex++
  1103. }
  1104. return targetIndex
  1105. }
  1106. func (r *Runtime) arrayproto_flatMap(call FunctionCall) Value {
  1107. o := call.This.ToObject(r)
  1108. l := toLength(o.self.getStr("length", nil))
  1109. callbackFn := r.toCallable(call.Argument(0))
  1110. thisArg := Undefined()
  1111. if len(call.Arguments) > 1 {
  1112. thisArg = call.Argument(1)
  1113. }
  1114. a := arraySpeciesCreate(o, 0)
  1115. r.flattenIntoArray(a, o, l, 0, 1, callbackFn, thisArg)
  1116. return a
  1117. }
  1118. func (r *Runtime) arrayproto_with(call FunctionCall) Value {
  1119. o := call.This.ToObject(r)
  1120. relativeIndex := call.Argument(0).ToInteger()
  1121. value := call.Argument(1)
  1122. length := toLength(o.self.getStr("length", nil))
  1123. actualIndex := int64(0)
  1124. if relativeIndex >= 0 {
  1125. actualIndex = relativeIndex
  1126. } else {
  1127. actualIndex = length + relativeIndex
  1128. }
  1129. if actualIndex >= length || actualIndex < 0 {
  1130. panic(r.newError(r.getRangeError(), "Invalid index %s", call.Argument(0).String()))
  1131. }
  1132. if src := r.checkStdArrayObj(o); src != nil {
  1133. a := make([]Value, 0, length)
  1134. for k := int64(0); k < length; k++ {
  1135. pk := valueInt(k)
  1136. var fromValue Value
  1137. if k == actualIndex {
  1138. fromValue = value
  1139. } else {
  1140. fromValue = src.values[pk]
  1141. }
  1142. a = append(a, fromValue)
  1143. }
  1144. return r.newArrayValues(a)
  1145. } else {
  1146. a := r.newArrayLength(length)
  1147. for k := int64(0); k < length; k++ {
  1148. pk := valueInt(k)
  1149. var fromValue Value
  1150. if k == actualIndex {
  1151. fromValue = value
  1152. } else {
  1153. fromValue = o.self.getIdx(pk, nil)
  1154. }
  1155. createDataPropertyOrThrow(a, pk, fromValue)
  1156. }
  1157. return a
  1158. }
  1159. }
  1160. func (r *Runtime) arrayproto_toReversed(call FunctionCall) Value {
  1161. o := call.This.ToObject(r)
  1162. length := toLength(o.self.getStr("length", nil))
  1163. if src := r.checkStdArrayObj(o); src != nil {
  1164. a := make([]Value, 0, length)
  1165. for k := int64(0); k < length; k++ {
  1166. from := valueInt(length - k - 1)
  1167. fromValue := src.values[from]
  1168. a = append(a, fromValue)
  1169. }
  1170. return r.newArrayValues(a)
  1171. } else {
  1172. a := r.newArrayLength(length)
  1173. for k := int64(0); k < length; k++ {
  1174. pk := valueInt(k)
  1175. from := valueInt(length - k - 1)
  1176. fromValue := o.self.getIdx(from, nil)
  1177. createDataPropertyOrThrow(a, pk, fromValue)
  1178. }
  1179. return a
  1180. }
  1181. }
  1182. func (r *Runtime) arrayproto_toSorted(call FunctionCall) Value {
  1183. var compareFn func(FunctionCall) Value
  1184. arg := call.Argument(0)
  1185. if arg != _undefined {
  1186. if arg, ok := arg.(*Object); ok {
  1187. compareFn, _ = arg.self.assertCallable()
  1188. }
  1189. if compareFn == nil {
  1190. panic(r.NewTypeError("The comparison function must be either a function or undefined"))
  1191. }
  1192. }
  1193. o := call.This.ToObject(r)
  1194. length := toLength(o.self.getStr("length", nil))
  1195. if length >= math.MaxUint32 {
  1196. panic(r.newError(r.getRangeError(), "Invalid array length"))
  1197. }
  1198. var a []Value
  1199. if src := r.checkStdArrayObj(o); src != nil {
  1200. a = make([]Value, length)
  1201. copy(a, src.values)
  1202. } else {
  1203. a = make([]Value, 0, length)
  1204. for i := int64(0); i < length; i++ {
  1205. idx := valueInt(i)
  1206. a = append(a, nilSafe(o.self.getIdx(idx, nil)))
  1207. }
  1208. }
  1209. ar := r.newArrayValues(a)
  1210. ctx := arraySortCtx{
  1211. obj: ar.self,
  1212. compare: compareFn,
  1213. }
  1214. sort.Stable(&ctx)
  1215. return ar
  1216. }
  1217. func (r *Runtime) arrayproto_toSpliced(call FunctionCall) Value {
  1218. o := call.This.ToObject(r)
  1219. length := toLength(o.self.getStr("length", nil))
  1220. actualStart := relToIdx(call.Argument(0).ToInteger(), length)
  1221. var actualSkipCount int64
  1222. if len(call.Arguments) == 1 {
  1223. actualSkipCount = length - actualStart
  1224. } else if len(call.Arguments) > 1 {
  1225. actualSkipCount = min(max(call.Argument(1).ToInteger(), 0), length-actualStart)
  1226. }
  1227. itemCount := max(int64(len(call.Arguments)-2), 0)
  1228. newLength := length - actualSkipCount + itemCount
  1229. if newLength >= maxInt {
  1230. panic(r.NewTypeError("Invalid array length"))
  1231. }
  1232. if src := r.checkStdArrayObj(o); src != nil {
  1233. var values []Value
  1234. if itemCount == actualSkipCount {
  1235. values = make([]Value, len(src.values))
  1236. copy(values, src.values)
  1237. } else {
  1238. values = make([]Value, newLength)
  1239. copy(values, src.values[:actualStart])
  1240. copy(values[actualStart+itemCount:], src.values[actualStart+actualSkipCount:])
  1241. }
  1242. if itemCount > 0 {
  1243. copy(values[actualStart:], call.Arguments[2:])
  1244. }
  1245. return r.newArrayValues(values)
  1246. } else {
  1247. a := r.newArrayLength(newLength)
  1248. var i int64
  1249. rl := actualStart + actualSkipCount
  1250. for i < actualStart {
  1251. pi := valueInt(i)
  1252. iValue := nilSafe(o.self.getIdx(pi, nil))
  1253. createDataPropertyOrThrow(a, pi, iValue)
  1254. i++
  1255. }
  1256. if itemCount > 0 {
  1257. for _, item := range call.Arguments[2:] {
  1258. createDataPropertyOrThrow(a, valueInt(i), nilSafe(item))
  1259. i++
  1260. }
  1261. }
  1262. for i < newLength {
  1263. pi := valueInt(i)
  1264. from := valueInt(rl)
  1265. fromValue := nilSafe(o.self.getIdx(from, nil))
  1266. createDataPropertyOrThrow(a, pi, fromValue)
  1267. i++
  1268. rl++
  1269. }
  1270. return a
  1271. }
  1272. }
  1273. func (r *Runtime) checkStdArrayObj(obj *Object) *arrayObject {
  1274. if arr, ok := obj.self.(*arrayObject); ok &&
  1275. arr.propValueCount == 0 &&
  1276. arr.length == uint32(len(arr.values)) &&
  1277. uint32(arr.objCount) == arr.length {
  1278. return arr
  1279. }
  1280. return nil
  1281. }
  1282. func (r *Runtime) checkStdArrayObjWithProto(obj *Object) *arrayObject {
  1283. if arr := r.checkStdArrayObj(obj); arr != nil {
  1284. if p1, ok := arr.prototype.self.(*arrayObject); ok && p1.propValueCount == 0 {
  1285. if p2, ok := p1.prototype.self.(*baseObject); ok && p2.prototype == nil {
  1286. p2.ensurePropOrder()
  1287. if p2.idxPropCount == 0 {
  1288. return arr
  1289. }
  1290. }
  1291. }
  1292. }
  1293. return nil
  1294. }
  1295. func (r *Runtime) checkStdArray(v Value) *arrayObject {
  1296. if obj, ok := v.(*Object); ok {
  1297. return r.checkStdArrayObj(obj)
  1298. }
  1299. return nil
  1300. }
  1301. func (r *Runtime) checkStdArrayIter(v Value) *arrayObject {
  1302. if arr := r.checkStdArray(v); arr != nil &&
  1303. arr.getSym(SymIterator, nil) == r.getArrayValues() {
  1304. return arr
  1305. }
  1306. return nil
  1307. }
  1308. func (r *Runtime) array_from(call FunctionCall) Value {
  1309. var mapFn func(FunctionCall) Value
  1310. if mapFnArg := call.Argument(1); mapFnArg != _undefined {
  1311. if mapFnObj, ok := mapFnArg.(*Object); ok {
  1312. if fn, ok := mapFnObj.self.assertCallable(); ok {
  1313. mapFn = fn
  1314. }
  1315. }
  1316. if mapFn == nil {
  1317. panic(r.NewTypeError("%s is not a function", mapFnArg))
  1318. }
  1319. }
  1320. t := call.Argument(2)
  1321. items := call.Argument(0)
  1322. if mapFn == nil && call.This == r.global.Array { // mapFn may mutate the array
  1323. if arr := r.checkStdArrayIter(items); arr != nil {
  1324. items := make([]Value, len(arr.values))
  1325. copy(items, arr.values)
  1326. return r.newArrayValues(items)
  1327. }
  1328. }
  1329. var ctor func(args []Value, newTarget *Object) *Object
  1330. if call.This != r.global.Array {
  1331. if o, ok := call.This.(*Object); ok {
  1332. if c := o.self.assertConstructor(); c != nil {
  1333. ctor = c
  1334. }
  1335. }
  1336. }
  1337. var arr *Object
  1338. if usingIterator := toMethod(r.getV(items, SymIterator)); usingIterator != nil {
  1339. if ctor != nil {
  1340. arr = ctor([]Value{}, nil)
  1341. } else {
  1342. arr = r.newArrayValues(nil)
  1343. }
  1344. iter := r.getIterator(items, usingIterator)
  1345. if mapFn == nil {
  1346. if a := r.checkStdArrayObjWithProto(arr); a != nil {
  1347. var values []Value
  1348. iter.iterate(func(val Value) {
  1349. values = append(values, val)
  1350. })
  1351. setArrayValues(a, values)
  1352. return arr
  1353. }
  1354. }
  1355. k := int64(0)
  1356. iter.iterate(func(val Value) {
  1357. if mapFn != nil {
  1358. val = mapFn(FunctionCall{This: t, Arguments: []Value{val, intToValue(k)}})
  1359. }
  1360. createDataPropertyOrThrow(arr, intToValue(k), val)
  1361. k++
  1362. })
  1363. arr.self.setOwnStr("length", intToValue(k), true)
  1364. } else {
  1365. arrayLike := items.ToObject(r)
  1366. l := toLength(arrayLike.self.getStr("length", nil))
  1367. if ctor != nil {
  1368. arr = ctor([]Value{intToValue(l)}, nil)
  1369. } else {
  1370. arr = r.newArrayValues(nil)
  1371. }
  1372. if mapFn == nil {
  1373. if a := r.checkStdArrayObjWithProto(arr); a != nil {
  1374. values := make([]Value, l)
  1375. for k := int64(0); k < l; k++ {
  1376. values[k] = nilSafe(arrayLike.self.getIdx(valueInt(k), nil))
  1377. }
  1378. setArrayValues(a, values)
  1379. return arr
  1380. }
  1381. }
  1382. for k := int64(0); k < l; k++ {
  1383. idx := valueInt(k)
  1384. item := arrayLike.self.getIdx(idx, nil)
  1385. if mapFn != nil {
  1386. item = mapFn(FunctionCall{This: t, Arguments: []Value{item, idx}})
  1387. } else {
  1388. item = nilSafe(item)
  1389. }
  1390. createDataPropertyOrThrow(arr, idx, item)
  1391. }
  1392. arr.self.setOwnStr("length", intToValue(l), true)
  1393. }
  1394. return arr
  1395. }
  1396. func (r *Runtime) array_isArray(call FunctionCall) Value {
  1397. if o, ok := call.Argument(0).(*Object); ok {
  1398. if isArray(o) {
  1399. return valueTrue
  1400. }
  1401. }
  1402. return valueFalse
  1403. }
  1404. func (r *Runtime) array_of(call FunctionCall) Value {
  1405. var ctor func(args []Value, newTarget *Object) *Object
  1406. if call.This != r.global.Array {
  1407. if o, ok := call.This.(*Object); ok {
  1408. if c := o.self.assertConstructor(); c != nil {
  1409. ctor = c
  1410. }
  1411. }
  1412. }
  1413. if ctor == nil {
  1414. values := make([]Value, len(call.Arguments))
  1415. copy(values, call.Arguments)
  1416. return r.newArrayValues(values)
  1417. }
  1418. l := intToValue(int64(len(call.Arguments)))
  1419. arr := ctor([]Value{l}, nil)
  1420. for i, val := range call.Arguments {
  1421. createDataPropertyOrThrow(arr, intToValue(int64(i)), val)
  1422. }
  1423. arr.self.setOwnStr("length", l, true)
  1424. return arr
  1425. }
  1426. func (r *Runtime) arrayIterProto_next(call FunctionCall) Value {
  1427. thisObj := r.toObject(call.This)
  1428. if iter, ok := thisObj.self.(*arrayIterObject); ok {
  1429. return iter.next()
  1430. }
  1431. panic(r.NewTypeError("Method Array Iterator.prototype.next called on incompatible receiver %s", r.objectproto_toString(FunctionCall{This: thisObj})))
  1432. }
  1433. func createArrayProtoTemplate() *objectTemplate {
  1434. t := newObjectTemplate()
  1435. t.protoFactory = func(r *Runtime) *Object {
  1436. return r.global.ObjectPrototype
  1437. }
  1438. t.putStr("length", func(r *Runtime) Value { return valueProp(_positiveZero, true, false, false) })
  1439. t.putStr("constructor", func(r *Runtime) Value { return valueProp(r.getArray(), true, false, true) })
  1440. t.putStr("at", func(r *Runtime) Value { return r.methodProp(r.arrayproto_at, "at", 1) })
  1441. t.putStr("concat", func(r *Runtime) Value { return r.methodProp(r.arrayproto_concat, "concat", 1) })
  1442. t.putStr("copyWithin", func(r *Runtime) Value { return r.methodProp(r.arrayproto_copyWithin, "copyWithin", 2) })
  1443. t.putStr("entries", func(r *Runtime) Value { return r.methodProp(r.arrayproto_entries, "entries", 0) })
  1444. t.putStr("every", func(r *Runtime) Value { return r.methodProp(r.arrayproto_every, "every", 1) })
  1445. t.putStr("fill", func(r *Runtime) Value { return r.methodProp(r.arrayproto_fill, "fill", 1) })
  1446. t.putStr("filter", func(r *Runtime) Value { return r.methodProp(r.arrayproto_filter, "filter", 1) })
  1447. t.putStr("find", func(r *Runtime) Value { return r.methodProp(r.arrayproto_find, "find", 1) })
  1448. t.putStr("findIndex", func(r *Runtime) Value { return r.methodProp(r.arrayproto_findIndex, "findIndex", 1) })
  1449. t.putStr("findLast", func(r *Runtime) Value { return r.methodProp(r.arrayproto_findLast, "findLast", 1) })
  1450. t.putStr("findLastIndex", func(r *Runtime) Value { return r.methodProp(r.arrayproto_findLastIndex, "findLastIndex", 1) })
  1451. t.putStr("flat", func(r *Runtime) Value { return r.methodProp(r.arrayproto_flat, "flat", 0) })
  1452. t.putStr("flatMap", func(r *Runtime) Value { return r.methodProp(r.arrayproto_flatMap, "flatMap", 1) })
  1453. t.putStr("forEach", func(r *Runtime) Value { return r.methodProp(r.arrayproto_forEach, "forEach", 1) })
  1454. t.putStr("includes", func(r *Runtime) Value { return r.methodProp(r.arrayproto_includes, "includes", 1) })
  1455. t.putStr("indexOf", func(r *Runtime) Value { return r.methodProp(r.arrayproto_indexOf, "indexOf", 1) })
  1456. t.putStr("join", func(r *Runtime) Value { return r.methodProp(r.arrayproto_join, "join", 1) })
  1457. t.putStr("keys", func(r *Runtime) Value { return r.methodProp(r.arrayproto_keys, "keys", 0) })
  1458. t.putStr("lastIndexOf", func(r *Runtime) Value { return r.methodProp(r.arrayproto_lastIndexOf, "lastIndexOf", 1) })
  1459. t.putStr("map", func(r *Runtime) Value { return r.methodProp(r.arrayproto_map, "map", 1) })
  1460. t.putStr("pop", func(r *Runtime) Value { return r.methodProp(r.arrayproto_pop, "pop", 0) })
  1461. t.putStr("push", func(r *Runtime) Value { return r.methodProp(r.arrayproto_push, "push", 1) })
  1462. t.putStr("reduce", func(r *Runtime) Value { return r.methodProp(r.arrayproto_reduce, "reduce", 1) })
  1463. t.putStr("reduceRight", func(r *Runtime) Value { return r.methodProp(r.arrayproto_reduceRight, "reduceRight", 1) })
  1464. t.putStr("reverse", func(r *Runtime) Value { return r.methodProp(r.arrayproto_reverse, "reverse", 0) })
  1465. t.putStr("shift", func(r *Runtime) Value { return r.methodProp(r.arrayproto_shift, "shift", 0) })
  1466. t.putStr("slice", func(r *Runtime) Value { return r.methodProp(r.arrayproto_slice, "slice", 2) })
  1467. t.putStr("some", func(r *Runtime) Value { return r.methodProp(r.arrayproto_some, "some", 1) })
  1468. t.putStr("sort", func(r *Runtime) Value { return r.methodProp(r.arrayproto_sort, "sort", 1) })
  1469. t.putStr("splice", func(r *Runtime) Value { return r.methodProp(r.arrayproto_splice, "splice", 2) })
  1470. t.putStr("toLocaleString", func(r *Runtime) Value { return r.methodProp(r.arrayproto_toLocaleString, "toLocaleString", 0) })
  1471. t.putStr("toString", func(r *Runtime) Value { return valueProp(r.getArrayToString(), true, false, true) })
  1472. t.putStr("unshift", func(r *Runtime) Value { return r.methodProp(r.arrayproto_unshift, "unshift", 1) })
  1473. t.putStr("with", func(r *Runtime) Value { return r.methodProp(r.arrayproto_with, "with", 2) })
  1474. t.putStr("toReversed", func(r *Runtime) Value { return r.methodProp(r.arrayproto_toReversed, "toReversed", 0) })
  1475. t.putStr("toSorted", func(r *Runtime) Value { return r.methodProp(r.arrayproto_toSorted, "toSorted", 1) })
  1476. t.putStr("toSpliced", func(r *Runtime) Value { return r.methodProp(r.arrayproto_toSpliced, "toSpliced", 2) })
  1477. t.putStr("values", func(r *Runtime) Value { return valueProp(r.getArrayValues(), true, false, true) })
  1478. t.putSym(SymIterator, func(r *Runtime) Value { return valueProp(r.getArrayValues(), true, false, true) })
  1479. t.putSym(SymUnscopables, func(r *Runtime) Value {
  1480. bl := r.newBaseObject(nil, classObject)
  1481. bl.setOwnStr("copyWithin", valueTrue, true)
  1482. bl.setOwnStr("entries", valueTrue, true)
  1483. bl.setOwnStr("fill", valueTrue, true)
  1484. bl.setOwnStr("find", valueTrue, true)
  1485. bl.setOwnStr("findIndex", valueTrue, true)
  1486. bl.setOwnStr("findLast", valueTrue, true)
  1487. bl.setOwnStr("findLastIndex", valueTrue, true)
  1488. bl.setOwnStr("flat", valueTrue, true)
  1489. bl.setOwnStr("flatMap", valueTrue, true)
  1490. bl.setOwnStr("includes", valueTrue, true)
  1491. bl.setOwnStr("keys", valueTrue, true)
  1492. bl.setOwnStr("values", valueTrue, true)
  1493. bl.setOwnStr("groupBy", valueTrue, true)
  1494. bl.setOwnStr("groupByToMap", valueTrue, true)
  1495. bl.setOwnStr("toReversed", valueTrue, true)
  1496. bl.setOwnStr("toSorted", valueTrue, true)
  1497. bl.setOwnStr("toSpliced", valueTrue, true)
  1498. return valueProp(bl.val, false, false, true)
  1499. })
  1500. return t
  1501. }
  1502. var arrayProtoTemplate *objectTemplate
  1503. var arrayProtoTemplateOnce sync.Once
  1504. func getArrayProtoTemplate() *objectTemplate {
  1505. arrayProtoTemplateOnce.Do(func() {
  1506. arrayProtoTemplate = createArrayProtoTemplate()
  1507. })
  1508. return arrayProtoTemplate
  1509. }
  1510. func (r *Runtime) getArrayPrototype() *Object {
  1511. ret := r.global.ArrayPrototype
  1512. if ret == nil {
  1513. ret = &Object{runtime: r}
  1514. r.global.ArrayPrototype = ret
  1515. r.newTemplatedArrayObject(getArrayProtoTemplate(), ret)
  1516. }
  1517. return ret
  1518. }
  1519. func (r *Runtime) getArray() *Object {
  1520. ret := r.global.Array
  1521. if ret == nil {
  1522. ret = &Object{runtime: r}
  1523. ret.self = r.createArray(ret)
  1524. r.global.Array = ret
  1525. }
  1526. return ret
  1527. }
  1528. func (r *Runtime) createArray(val *Object) objectImpl {
  1529. o := r.newNativeFuncConstructObj(val, r.builtin_newArray, "Array", r.getArrayPrototype(), 1)
  1530. o._putProp("from", r.newNativeFunc(r.array_from, "from", 1), true, false, true)
  1531. o._putProp("isArray", r.newNativeFunc(r.array_isArray, "isArray", 1), true, false, true)
  1532. o._putProp("of", r.newNativeFunc(r.array_of, "of", 0), true, false, true)
  1533. r.putSpeciesReturnThis(o)
  1534. return o
  1535. }
  1536. func (r *Runtime) createArrayIterProto(val *Object) objectImpl {
  1537. o := newBaseObjectObj(val, r.getIteratorPrototype(), classObject)
  1538. o._putProp("next", r.newNativeFunc(r.arrayIterProto_next, "next", 0), true, false, true)
  1539. o._putSym(SymToStringTag, valueProp(asciiString(classArrayIterator), false, false, true))
  1540. return o
  1541. }
  1542. func (r *Runtime) getArrayValues() *Object {
  1543. ret := r.global.arrayValues
  1544. if ret == nil {
  1545. ret = r.newNativeFunc(r.arrayproto_values, "values", 0)
  1546. r.global.arrayValues = ret
  1547. }
  1548. return ret
  1549. }
  1550. func (r *Runtime) getArrayToString() *Object {
  1551. ret := r.global.arrayToString
  1552. if ret == nil {
  1553. ret = r.newNativeFunc(r.arrayproto_toString, "toString", 0)
  1554. r.global.arrayToString = ret
  1555. }
  1556. return ret
  1557. }
  1558. func (r *Runtime) getArrayIteratorPrototype() *Object {
  1559. var o *Object
  1560. if o = r.global.ArrayIteratorPrototype; o == nil {
  1561. o = &Object{runtime: r}
  1562. r.global.ArrayIteratorPrototype = o
  1563. o.self = r.createArrayIterProto(o)
  1564. }
  1565. return o
  1566. }
  1567. type sortable interface {
  1568. sortLen() int
  1569. sortGet(int) Value
  1570. swap(int, int)
  1571. }
  1572. type arraySortCtx struct {
  1573. obj sortable
  1574. compare func(FunctionCall) Value
  1575. }
  1576. func (a *arraySortCtx) sortCompare(x, y Value) int {
  1577. if x == nil && y == nil {
  1578. return 0
  1579. }
  1580. if x == nil {
  1581. return 1
  1582. }
  1583. if y == nil {
  1584. return -1
  1585. }
  1586. if x == _undefined && y == _undefined {
  1587. return 0
  1588. }
  1589. if x == _undefined {
  1590. return 1
  1591. }
  1592. if y == _undefined {
  1593. return -1
  1594. }
  1595. if a.compare != nil {
  1596. f := a.compare(FunctionCall{
  1597. This: _undefined,
  1598. Arguments: []Value{x, y},
  1599. }).ToFloat()
  1600. if f > 0 {
  1601. return 1
  1602. }
  1603. if f < 0 {
  1604. return -1
  1605. }
  1606. if math.Signbit(f) {
  1607. return -1
  1608. }
  1609. return 0
  1610. }
  1611. return x.toString().CompareTo(y.toString())
  1612. }
  1613. // sort.Interface
  1614. func (a *arraySortCtx) Len() int {
  1615. return a.obj.sortLen()
  1616. }
  1617. func (a *arraySortCtx) Less(j, k int) bool {
  1618. return a.sortCompare(a.obj.sortGet(j), a.obj.sortGet(k)) < 0
  1619. }
  1620. func (a *arraySortCtx) Swap(j, k int) {
  1621. a.obj.swap(j, k)
  1622. }