@@ -95,40 +95,56 @@ export class Slice {
9595 * @returns {NormalizedSlice } The normalized slice parameters.
9696 */
9797 public normalize ( containerLength : number ) : NormalizedSlice {
98- // TODO: Need refactor
9998 let step = this . step ?? 1 ;
10099
101- if ( step === 0 ) {
102- throw new IndexError ( "Step cannot be 0." ) ;
103- }
100+ if ( step > 0 ) {
101+ let start = this . start ?? 0 ;
102+ let end = this . end ?? containerLength ;
104103
105- let defaultEnd = ( step < 0 && this . end === undefined ) ? - 1 : undefined ;
104+ [ start , end , step ] = [ Math . round ( start ) , Math . round ( end ) , Math . round ( step ) ] ;
106105
107- let start = this . start ?? ( step > 0 ? 0 : containerLength - 1 ) ;
108- let end = this . end ?? ( step > 0 ? containerLength : - 1 ) ;
106+ start = normalizeIndex ( start , containerLength , false ) ;
107+ end = normalizeIndex ( end , containerLength , false ) ;
109108
110- start = Math . round ( start ) ;
111- end = Math . round ( end ) ;
112- step = Math . round ( step ) ;
109+ if ( start >= containerLength ) {
110+ start = end = containerLength - 1 ;
111+ }
113112
114- start = normalizeIndex ( start , containerLength , false ) ;
115- end = normalizeIndex ( end , containerLength , false ) ;
113+ start = this . squeezeInBounds ( start , 0 , containerLength - 1 ) ;
114+ end = this . squeezeInBounds ( end , 0 , containerLength ) ;
116115
117- if ( step > 0 && start >= containerLength ) {
118- start = end = containerLength - 1 ;
119- } else if ( step < 0 && start < 0 ) {
120- start = end = 0 ;
121- defaultEnd = 0 ;
122- }
116+ if ( end < start ) {
117+ end = start ;
118+ }
119+
120+ return new NormalizedSlice ( start , end , step ) ;
121+ } else if ( step < 0 ) {
122+ let start = this . start ?? containerLength - 1 ;
123+ let end = this . end ?? - 1 ;
124+
125+ [ start , end , step ] = [ Math . round ( start ) , Math . round ( end ) , Math . round ( step ) ] ;
126+
127+ start = normalizeIndex ( start , containerLength , false ) ;
128+
129+ if ( ! ( this . end === undefined ) ) {
130+ end = normalizeIndex ( end , containerLength , false ) ;
131+ }
132+
133+ if ( start < 0 ) {
134+ start = end = 0 ;
135+ }
136+
137+ start = this . squeezeInBounds ( start , 0 , containerLength - 1 ) ;
138+ end = this . squeezeInBounds ( end , - 1 , containerLength ) ;
123139
124- start = this . squeezeInBounds ( start , 0 , containerLength - 1 ) ;
125- end = this . squeezeInBounds ( end , step > 0 ? 0 : - 1 , containerLength ) ;
140+ if ( end > start ) {
141+ end = start ;
142+ }
126143
127- if ( ( step > 0 && end < start ) || ( step < 0 && end > start ) ) {
128- end = start ;
144+ return new NormalizedSlice ( start , end , step ) ;
129145 }
130146
131- return new NormalizedSlice ( start , defaultEnd ?? end , step ) ;
147+ throw new IndexError ( "Step cannot be 0." ) ;
132148 }
133149
134150 /**
0 commit comments