-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (44 loc) · 1.28 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'use strict';
var extend = require('extend-shallow');
var isObject = require('isobject');
module.exports = function sort(arr, config) {
if (!Array.isArray(arr)) {
throw new TypeError('expected an array');
}
if (arr.length === 1) {
return arr;
}
if (!isObject(config)) {
throw new TypeError('expected config to be an object');
}
if (typeof config.prop !== 'string') {
throw new TypeError('expected config.prop to be a string (the key to sort by)');
}
if (!Array.isArray(config.values)) {
throw new TypeError('expected config.values to be an array of strings');
}
var opts = extend({normalize: normalize}, config);
var res = new Array(opts.values.length);
var rest = [];
var normalized = opts.values.map(function(ele) {
return opts.normalize(ele);
});
// this is a bit faster than sort
for (var i = 0; i < arr.length; i++) {
var ele = arr[i];
if (!isObject(ele)) {
throw new TypeError('expected an array of objects');
}
var val = ele[opts.prop];
var idx = normalized.indexOf(opts.normalize(val));
if (idx !== -1) {
res.splice(idx, 1, ele);
} else {
rest.push(ele);
}
}
return res.concat(rest).filter(Boolean);
};
function normalize(str) {
return str.replace(/[\s\W]/g, '').toLowerCase();
}