Open wingmeng opened 5 years ago
一般
优秀、良好、一般、差劲
prototype
;function swapArrItem(arr, srcIdx, targetIdx) {
if (!Array.isArray(arr)) {
throw Error(`\`${arr}\` is not a array`);
}
if (isNaN(srcIdx) || isNaN(targetIdx)) {
throw Error(`index is not a number`);
}
let len = arr.length - 1;
srcIdx = srcIdx < 0 ? 0 : srcIdx;
srcIdx = srcIdx > len ? len : srcIdx;
targetIdx = targetIdx < 0 ? 0 : targetIdx;
targetIdx = targetIdx > len ? len : targetIdx;
arr = [...arr];
[arr[srcIdx], arr[targetIdx]] = [arr[targetIdx], arr[srcIdx]];
return arr;
}
function moveArrItem(arr, idx, method) {
const _toBoundary = (arr1, idx, handle) => {
let temp = arr1.splice(idx, 1)[0];
arr1[handle](temp);
return arr1;
};
if (!Array.isArray(arr)) {
throw Error(`\`${arr}\` is not a array`);
}
arr = [...arr];
switch(method) {
case 'first':
return _toBoundary(arr, idx, 'unshift');
case 'last':
return _toBoundary(arr, idx, 'push');
case 'forward':
return swapArrItem(arr, idx, idx - 1);
case 'backward':
return swapArrItem(arr, idx, idx + 1);
default:
throw Error(`${method} is not a available parameter`);
}
}
题目:
我的答案:
既然题目中用了
let
,那我就不客气了,ES6 直接用起。:tada: 主要原理是数组的splice
操作,然后是处理各种边界情况。 封装了一下,使用链式调用,使方法看起来更语义化。