@@ -96,7 +96,7 @@ function parseEncoding(str, i) {
96
96
*/
97
97
98
98
function getEncodingPriority ( encoding , accepted , index ) {
99
- var priority = { o : - 1 , q : 0 , s : 0 } ;
99
+ var priority = { encoding : encoding , o : - 1 , q : 0 , s : 0 } ;
100
100
101
101
for ( var i = 0 ; i < accepted . length ; i ++ ) {
102
102
var spec = specify ( encoding , accepted [ i ] , index ) ;
@@ -123,6 +123,7 @@ function specify(encoding, spec, index) {
123
123
}
124
124
125
125
return {
126
+ encoding : encoding ,
126
127
i : index ,
127
128
o : spec . i ,
128
129
q : spec . q ,
@@ -135,14 +136,34 @@ function specify(encoding, spec, index) {
135
136
* @public
136
137
*/
137
138
138
- function preferredEncodings ( accept , provided ) {
139
+ function preferredEncodings ( accept , provided , preferred ) {
139
140
var accepts = parseAcceptEncoding ( accept || '' ) ;
140
141
142
+ var comparator = preferred ? function comparator ( a , b ) {
143
+ if ( a . q !== b . q ) {
144
+ return b . q - a . q // higher quality first
145
+ }
146
+
147
+ var aPreferred = preferred . indexOf ( a . encoding )
148
+ var bPreferred = preferred . indexOf ( b . encoding )
149
+
150
+ if ( aPreferred === - 1 && bPreferred === - 1 ) {
151
+ // consider the original specifity/order
152
+ return ( b . s - a . s ) || ( a . o - b . o ) || ( a . i - b . i )
153
+ }
154
+
155
+ if ( aPreferred !== - 1 && bPreferred !== - 1 ) {
156
+ return aPreferred - bPreferred // consider the preferred order
157
+ }
158
+
159
+ return aPreferred === - 1 ? 1 : - 1 // preferred first
160
+ } : compareSpecs ;
161
+
141
162
if ( ! provided ) {
142
163
// sorted list of all encodings
143
164
return accepts
144
165
. filter ( isQuality )
145
- . sort ( compareSpecs )
166
+ . sort ( comparator )
146
167
. map ( getFullEncoding ) ;
147
168
}
148
169
@@ -151,7 +172,7 @@ function preferredEncodings(accept, provided) {
151
172
} ) ;
152
173
153
174
// sorted list of accepted encodings
154
- return priorities . filter ( isQuality ) . sort ( compareSpecs ) . map ( function getEncoding ( priority ) {
175
+ return priorities . filter ( isQuality ) . sort ( comparator ) . map ( function getEncoding ( priority ) {
155
176
return provided [ priorities . indexOf ( priority ) ] ;
156
177
} ) ;
157
178
}
@@ -162,7 +183,7 @@ function preferredEncodings(accept, provided) {
162
183
*/
163
184
164
185
function compareSpecs ( a , b ) {
165
- return ( b . q - a . q ) || ( b . s - a . s ) || ( a . o - b . o ) || ( a . i - b . i ) || 0 ;
186
+ return ( b . q - a . q ) || ( b . s - a . s ) || ( a . o - b . o ) || ( a . i - b . i ) ;
166
187
}
167
188
168
189
/**
0 commit comments