builtin_array.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  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) checkStdArrayObj(obj *Object) *arrayObject {
  1119. if arr, ok := obj.self.(*arrayObject); ok &&
  1120. arr.propValueCount == 0 &&
  1121. arr.length == uint32(len(arr.values)) &&
  1122. uint32(arr.objCount) == arr.length {
  1123. return arr
  1124. }
  1125. return nil
  1126. }
  1127. func (r *Runtime) checkStdArrayObjWithProto(obj *Object) *arrayObject {
  1128. if arr := r.checkStdArrayObj(obj); arr != nil {
  1129. if p1, ok := arr.prototype.self.(*arrayObject); ok && p1.propValueCount == 0 {
  1130. if p2, ok := p1.prototype.self.(*baseObject); ok && p2.prototype == nil {
  1131. p2.ensurePropOrder()
  1132. if p2.idxPropCount == 0 {
  1133. return arr
  1134. }
  1135. }
  1136. }
  1137. }
  1138. return nil
  1139. }
  1140. func (r *Runtime) checkStdArray(v Value) *arrayObject {
  1141. if obj, ok := v.(*Object); ok {
  1142. return r.checkStdArrayObj(obj)
  1143. }
  1144. return nil
  1145. }
  1146. func (r *Runtime) checkStdArrayIter(v Value) *arrayObject {
  1147. if arr := r.checkStdArray(v); arr != nil &&
  1148. arr.getSym(SymIterator, nil) == r.getArrayValues() {
  1149. return arr
  1150. }
  1151. return nil
  1152. }
  1153. func (r *Runtime) array_from(call FunctionCall) Value {
  1154. var mapFn func(FunctionCall) Value
  1155. if mapFnArg := call.Argument(1); mapFnArg != _undefined {
  1156. if mapFnObj, ok := mapFnArg.(*Object); ok {
  1157. if fn, ok := mapFnObj.self.assertCallable(); ok {
  1158. mapFn = fn
  1159. }
  1160. }
  1161. if mapFn == nil {
  1162. panic(r.NewTypeError("%s is not a function", mapFnArg))
  1163. }
  1164. }
  1165. t := call.Argument(2)
  1166. items := call.Argument(0)
  1167. if mapFn == nil && call.This == r.global.Array { // mapFn may mutate the array
  1168. if arr := r.checkStdArrayIter(items); arr != nil {
  1169. items := make([]Value, len(arr.values))
  1170. copy(items, arr.values)
  1171. return r.newArrayValues(items)
  1172. }
  1173. }
  1174. var ctor func(args []Value, newTarget *Object) *Object
  1175. if call.This != r.global.Array {
  1176. if o, ok := call.This.(*Object); ok {
  1177. if c := o.self.assertConstructor(); c != nil {
  1178. ctor = c
  1179. }
  1180. }
  1181. }
  1182. var arr *Object
  1183. if usingIterator := toMethod(r.getV(items, SymIterator)); usingIterator != nil {
  1184. if ctor != nil {
  1185. arr = ctor([]Value{}, nil)
  1186. } else {
  1187. arr = r.newArrayValues(nil)
  1188. }
  1189. iter := r.getIterator(items, usingIterator)
  1190. if mapFn == nil {
  1191. if a := r.checkStdArrayObjWithProto(arr); a != nil {
  1192. var values []Value
  1193. iter.iterate(func(val Value) {
  1194. values = append(values, val)
  1195. })
  1196. setArrayValues(a, values)
  1197. return arr
  1198. }
  1199. }
  1200. k := int64(0)
  1201. iter.iterate(func(val Value) {
  1202. if mapFn != nil {
  1203. val = mapFn(FunctionCall{This: t, Arguments: []Value{val, intToValue(k)}})
  1204. }
  1205. createDataPropertyOrThrow(arr, intToValue(k), val)
  1206. k++
  1207. })
  1208. arr.self.setOwnStr("length", intToValue(k), true)
  1209. } else {
  1210. arrayLike := items.ToObject(r)
  1211. l := toLength(arrayLike.self.getStr("length", nil))
  1212. if ctor != nil {
  1213. arr = ctor([]Value{intToValue(l)}, nil)
  1214. } else {
  1215. arr = r.newArrayValues(nil)
  1216. }
  1217. if mapFn == nil {
  1218. if a := r.checkStdArrayObjWithProto(arr); a != nil {
  1219. values := make([]Value, l)
  1220. for k := int64(0); k < l; k++ {
  1221. values[k] = nilSafe(arrayLike.self.getIdx(valueInt(k), nil))
  1222. }
  1223. setArrayValues(a, values)
  1224. return arr
  1225. }
  1226. }
  1227. for k := int64(0); k < l; k++ {
  1228. idx := valueInt(k)
  1229. item := arrayLike.self.getIdx(idx, nil)
  1230. if mapFn != nil {
  1231. item = mapFn(FunctionCall{This: t, Arguments: []Value{item, idx}})
  1232. } else {
  1233. item = nilSafe(item)
  1234. }
  1235. createDataPropertyOrThrow(arr, idx, item)
  1236. }
  1237. arr.self.setOwnStr("length", intToValue(l), true)
  1238. }
  1239. return arr
  1240. }
  1241. func (r *Runtime) array_isArray(call FunctionCall) Value {
  1242. if o, ok := call.Argument(0).(*Object); ok {
  1243. if isArray(o) {
  1244. return valueTrue
  1245. }
  1246. }
  1247. return valueFalse
  1248. }
  1249. func (r *Runtime) array_of(call FunctionCall) Value {
  1250. var ctor func(args []Value, newTarget *Object) *Object
  1251. if call.This != r.global.Array {
  1252. if o, ok := call.This.(*Object); ok {
  1253. if c := o.self.assertConstructor(); c != nil {
  1254. ctor = c
  1255. }
  1256. }
  1257. }
  1258. if ctor == nil {
  1259. values := make([]Value, len(call.Arguments))
  1260. copy(values, call.Arguments)
  1261. return r.newArrayValues(values)
  1262. }
  1263. l := intToValue(int64(len(call.Arguments)))
  1264. arr := ctor([]Value{l}, nil)
  1265. for i, val := range call.Arguments {
  1266. createDataPropertyOrThrow(arr, intToValue(int64(i)), val)
  1267. }
  1268. arr.self.setOwnStr("length", l, true)
  1269. return arr
  1270. }
  1271. func (r *Runtime) arrayIterProto_next(call FunctionCall) Value {
  1272. thisObj := r.toObject(call.This)
  1273. if iter, ok := thisObj.self.(*arrayIterObject); ok {
  1274. return iter.next()
  1275. }
  1276. panic(r.NewTypeError("Method Array Iterator.prototype.next called on incompatible receiver %s", r.objectproto_toString(FunctionCall{This: thisObj})))
  1277. }
  1278. func createArrayProtoTemplate() *objectTemplate {
  1279. t := newObjectTemplate()
  1280. t.protoFactory = func(r *Runtime) *Object {
  1281. return r.global.ObjectPrototype
  1282. }
  1283. t.putStr("length", func(r *Runtime) Value { return valueProp(_positiveZero, true, false, false) })
  1284. t.putStr("constructor", func(r *Runtime) Value { return valueProp(r.getArray(), true, false, true) })
  1285. t.putStr("at", func(r *Runtime) Value { return r.methodProp(r.arrayproto_at, "at", 1) })
  1286. t.putStr("concat", func(r *Runtime) Value { return r.methodProp(r.arrayproto_concat, "concat", 1) })
  1287. t.putStr("copyWithin", func(r *Runtime) Value { return r.methodProp(r.arrayproto_copyWithin, "copyWithin", 2) })
  1288. t.putStr("entries", func(r *Runtime) Value { return r.methodProp(r.arrayproto_entries, "entries", 0) })
  1289. t.putStr("every", func(r *Runtime) Value { return r.methodProp(r.arrayproto_every, "every", 1) })
  1290. t.putStr("fill", func(r *Runtime) Value { return r.methodProp(r.arrayproto_fill, "fill", 1) })
  1291. t.putStr("filter", func(r *Runtime) Value { return r.methodProp(r.arrayproto_filter, "filter", 1) })
  1292. t.putStr("find", func(r *Runtime) Value { return r.methodProp(r.arrayproto_find, "find", 1) })
  1293. t.putStr("findIndex", func(r *Runtime) Value { return r.methodProp(r.arrayproto_findIndex, "findIndex", 1) })
  1294. t.putStr("findLast", func(r *Runtime) Value { return r.methodProp(r.arrayproto_findLast, "findLast", 1) })
  1295. t.putStr("findLastIndex", func(r *Runtime) Value { return r.methodProp(r.arrayproto_findLastIndex, "findLastIndex", 1) })
  1296. t.putStr("flat", func(r *Runtime) Value { return r.methodProp(r.arrayproto_flat, "flat", 0) })
  1297. t.putStr("flatMap", func(r *Runtime) Value { return r.methodProp(r.arrayproto_flatMap, "flatMap", 1) })
  1298. t.putStr("forEach", func(r *Runtime) Value { return r.methodProp(r.arrayproto_forEach, "forEach", 1) })
  1299. t.putStr("includes", func(r *Runtime) Value { return r.methodProp(r.arrayproto_includes, "includes", 1) })
  1300. t.putStr("indexOf", func(r *Runtime) Value { return r.methodProp(r.arrayproto_indexOf, "indexOf", 1) })
  1301. t.putStr("join", func(r *Runtime) Value { return r.methodProp(r.arrayproto_join, "join", 1) })
  1302. t.putStr("keys", func(r *Runtime) Value { return r.methodProp(r.arrayproto_keys, "keys", 0) })
  1303. t.putStr("lastIndexOf", func(r *Runtime) Value { return r.methodProp(r.arrayproto_lastIndexOf, "lastIndexOf", 1) })
  1304. t.putStr("map", func(r *Runtime) Value { return r.methodProp(r.arrayproto_map, "map", 1) })
  1305. t.putStr("pop", func(r *Runtime) Value { return r.methodProp(r.arrayproto_pop, "pop", 0) })
  1306. t.putStr("push", func(r *Runtime) Value { return r.methodProp(r.arrayproto_push, "push", 1) })
  1307. t.putStr("reduce", func(r *Runtime) Value { return r.methodProp(r.arrayproto_reduce, "reduce", 1) })
  1308. t.putStr("reduceRight", func(r *Runtime) Value { return r.methodProp(r.arrayproto_reduceRight, "reduceRight", 1) })
  1309. t.putStr("reverse", func(r *Runtime) Value { return r.methodProp(r.arrayproto_reverse, "reverse", 0) })
  1310. t.putStr("shift", func(r *Runtime) Value { return r.methodProp(r.arrayproto_shift, "shift", 0) })
  1311. t.putStr("slice", func(r *Runtime) Value { return r.methodProp(r.arrayproto_slice, "slice", 2) })
  1312. t.putStr("some", func(r *Runtime) Value { return r.methodProp(r.arrayproto_some, "some", 1) })
  1313. t.putStr("sort", func(r *Runtime) Value { return r.methodProp(r.arrayproto_sort, "sort", 1) })
  1314. t.putStr("splice", func(r *Runtime) Value { return r.methodProp(r.arrayproto_splice, "splice", 2) })
  1315. t.putStr("toLocaleString", func(r *Runtime) Value { return r.methodProp(r.arrayproto_toLocaleString, "toLocaleString", 0) })
  1316. t.putStr("toString", func(r *Runtime) Value { return valueProp(r.getArrayToString(), true, false, true) })
  1317. t.putStr("unshift", func(r *Runtime) Value { return r.methodProp(r.arrayproto_unshift, "unshift", 1) })
  1318. t.putStr("values", func(r *Runtime) Value { return valueProp(r.getArrayValues(), true, false, true) })
  1319. t.putSym(SymIterator, func(r *Runtime) Value { return valueProp(r.getArrayValues(), true, false, true) })
  1320. t.putSym(SymUnscopables, func(r *Runtime) Value {
  1321. bl := r.newBaseObject(nil, classObject)
  1322. bl.setOwnStr("copyWithin", valueTrue, true)
  1323. bl.setOwnStr("entries", valueTrue, true)
  1324. bl.setOwnStr("fill", valueTrue, true)
  1325. bl.setOwnStr("find", valueTrue, true)
  1326. bl.setOwnStr("findIndex", valueTrue, true)
  1327. bl.setOwnStr("findLast", valueTrue, true)
  1328. bl.setOwnStr("findLastIndex", valueTrue, true)
  1329. bl.setOwnStr("flat", valueTrue, true)
  1330. bl.setOwnStr("flatMap", valueTrue, true)
  1331. bl.setOwnStr("includes", valueTrue, true)
  1332. bl.setOwnStr("keys", valueTrue, true)
  1333. bl.setOwnStr("values", valueTrue, true)
  1334. bl.setOwnStr("groupBy", valueTrue, true)
  1335. bl.setOwnStr("groupByToMap", valueTrue, true)
  1336. return valueProp(bl.val, false, false, true)
  1337. })
  1338. return t
  1339. }
  1340. var arrayProtoTemplate *objectTemplate
  1341. var arrayProtoTemplateOnce sync.Once
  1342. func getArrayProtoTemplate() *objectTemplate {
  1343. arrayProtoTemplateOnce.Do(func() {
  1344. arrayProtoTemplate = createArrayProtoTemplate()
  1345. })
  1346. return arrayProtoTemplate
  1347. }
  1348. func (r *Runtime) getArrayPrototype() *Object {
  1349. ret := r.global.ArrayPrototype
  1350. if ret == nil {
  1351. ret = &Object{runtime: r}
  1352. r.global.ArrayPrototype = ret
  1353. r.newTemplatedArrayObject(getArrayProtoTemplate(), ret)
  1354. }
  1355. return ret
  1356. }
  1357. func (r *Runtime) getArray() *Object {
  1358. ret := r.global.Array
  1359. if ret == nil {
  1360. ret = &Object{runtime: r}
  1361. ret.self = r.createArray(ret)
  1362. r.global.Array = ret
  1363. }
  1364. return ret
  1365. }
  1366. func (r *Runtime) createArray(val *Object) objectImpl {
  1367. o := r.newNativeFuncConstructObj(val, r.builtin_newArray, "Array", r.getArrayPrototype(), 1)
  1368. o._putProp("from", r.newNativeFunc(r.array_from, "from", 1), true, false, true)
  1369. o._putProp("isArray", r.newNativeFunc(r.array_isArray, "isArray", 1), true, false, true)
  1370. o._putProp("of", r.newNativeFunc(r.array_of, "of", 0), true, false, true)
  1371. r.putSpeciesReturnThis(o)
  1372. return o
  1373. }
  1374. func (r *Runtime) createArrayIterProto(val *Object) objectImpl {
  1375. o := newBaseObjectObj(val, r.getIteratorPrototype(), classObject)
  1376. o._putProp("next", r.newNativeFunc(r.arrayIterProto_next, "next", 0), true, false, true)
  1377. o._putSym(SymToStringTag, valueProp(asciiString(classArrayIterator), false, false, true))
  1378. return o
  1379. }
  1380. func (r *Runtime) getArrayValues() *Object {
  1381. ret := r.global.arrayValues
  1382. if ret == nil {
  1383. ret = r.newNativeFunc(r.arrayproto_values, "values", 0)
  1384. r.global.arrayValues = ret
  1385. }
  1386. return ret
  1387. }
  1388. func (r *Runtime) getArrayToString() *Object {
  1389. ret := r.global.arrayToString
  1390. if ret == nil {
  1391. ret = r.newNativeFunc(r.arrayproto_toString, "toString", 0)
  1392. r.global.arrayToString = ret
  1393. }
  1394. return ret
  1395. }
  1396. func (r *Runtime) getArrayIteratorPrototype() *Object {
  1397. var o *Object
  1398. if o = r.global.ArrayIteratorPrototype; o == nil {
  1399. o = &Object{runtime: r}
  1400. r.global.ArrayIteratorPrototype = o
  1401. o.self = r.createArrayIterProto(o)
  1402. }
  1403. return o
  1404. }
  1405. type sortable interface {
  1406. sortLen() int
  1407. sortGet(int) Value
  1408. swap(int, int)
  1409. }
  1410. type arraySortCtx struct {
  1411. obj sortable
  1412. compare func(FunctionCall) Value
  1413. }
  1414. func (a *arraySortCtx) sortCompare(x, y Value) int {
  1415. if x == nil && y == nil {
  1416. return 0
  1417. }
  1418. if x == nil {
  1419. return 1
  1420. }
  1421. if y == nil {
  1422. return -1
  1423. }
  1424. if x == _undefined && y == _undefined {
  1425. return 0
  1426. }
  1427. if x == _undefined {
  1428. return 1
  1429. }
  1430. if y == _undefined {
  1431. return -1
  1432. }
  1433. if a.compare != nil {
  1434. f := a.compare(FunctionCall{
  1435. This: _undefined,
  1436. Arguments: []Value{x, y},
  1437. }).ToFloat()
  1438. if f > 0 {
  1439. return 1
  1440. }
  1441. if f < 0 {
  1442. return -1
  1443. }
  1444. if math.Signbit(f) {
  1445. return -1
  1446. }
  1447. return 0
  1448. }
  1449. return x.toString().CompareTo(y.toString())
  1450. }
  1451. // sort.Interface
  1452. func (a *arraySortCtx) Len() int {
  1453. return a.obj.sortLen()
  1454. }
  1455. func (a *arraySortCtx) Less(j, k int) bool {
  1456. return a.sortCompare(a.obj.sortGet(j), a.obj.sortGet(k)) < 0
  1457. }
  1458. func (a *arraySortCtx) Swap(j, k int) {
  1459. a.obj.swap(j, k)
  1460. }