source: frontend/node_modules/hoopy/index.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 1.9 KB
Line 
1'use strict'
2
3class Hoopy extends Array {
4 constructor (size) {
5 let index, isIndexOverflowed
6
7 if (! isPositiveInteger(size)) {
8 throw new TypeError('Argument `size` must be a positive integer.')
9 }
10
11 super(size)
12
13 this.grow = by => {
14 if (! isPositiveInteger(by)) {
15 throw new TypeError('Argument `by` must be a positive integer.')
16 }
17
18 let i
19 const newSize = size + by
20
21 for (i = size; i < newSize; ++i) {
22 this[i] = undefined
23 }
24
25 if (isIndexOverflowed) {
26 for (i = 0; i <= index; ++i) {
27 let j = size + i
28 if (j >= newSize) {
29 j %= newSize
30 }
31 this[j] = this[i]
32 this[i] = undefined
33 }
34 }
35
36 size = newSize
37 }
38
39 return new Proxy(this, {
40 get (target, key) {
41 if (isInteger(key)) {
42 return target[getIndex(key, size)]
43 }
44
45 return target[key]
46 },
47
48 set (target, key, value) {
49 if (isInteger(key)) {
50 index = getIndex(key, size)
51 target[index] = value
52
53 if (Math.abs(key) >= size) {
54 isIndexOverflowed = true
55 } else {
56 isIndexOverflowed = false
57 }
58 } else {
59 target[key] = value
60 }
61 return true
62 }
63 })
64 }
65}
66
67function isPositiveInteger (thing) {
68 return isInteger(thing) && thing > 0
69}
70
71function isInteger (thing) {
72 try {
73 return +thing % 1 === 0
74 } catch (error) {
75 // Coercing symbols to numbers throws an error
76 }
77
78 return false
79}
80
81function getIndex (key, size) {
82 if (key === 0) {
83 return 0
84 }
85
86 if (key < 0) {
87 return (size - Math.abs(key)) % size
88 }
89
90 return key % size
91}
92
93function nop () {
94 throw new Error('Not implemented')
95}
96
97Hoopy.prototype.push = nop
98Hoopy.prototype.pop = nop
99Hoopy.prototype.shift = nop
100Hoopy.prototype.unshift = nop
101
102module.exports = Hoopy
103
Note: See TracBrowser for help on using the repository browser.