area51
Version:
Experimental prototypes of alien things built in JavaScript. The bits may end up living in a different package.
106 lines (85 loc) • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.swap = swap;
exports.remove = remove;
exports.add = add;
exports.insert = insert;
exports.reverse = reverse;
exports.copy = copy;
exports.clone = clone;
var stringify = Object.prototype.toString;
function swap(array, i, j) {
var old = array[i];
array[i] = array[j];
array[j] = old;
}
function remove(array, index) {
return array.splice(index, 1);
}
function add(array, item, index) {
index = index || array.length;
array[index] = item;
return array;
}
function insert(array, index, item) {
array.splice(index, 0, item);
return array;
}
function reverse(array, startIndex, length) {
var i = startIndex || 0,
j = (length || array.length) - 1;
for (; i < j; i++, j--) {
var old = array[i];
array[i] = array[j];
array[j] = old;
}
}
/**
* Copies an array to another array. The way an array is copied can be changed by providing
* a copy function that accepts the source array, current index, destination array, destination index.
*
* @example
* var copy = require("kit/lib/copy"),
* arrayCopy = require("kit/lib/array-copy");
*
* // array copy that clones objects
* arrayCopy(["one", {test: "value"}], 0, [], 0, null, copy);
*
*
*
* @param {Array} source The array that hold the values that will be copied.
* @param {Number} [sourceIndex] The index position that the sourceIndex should start.
* @param {Array} destination The array that the values will be copied to.
* @param {Number} [destinationIndex] The position of the destination array that the copy should start at.
* @param {Number} [length] The number of items that should be copied.
* @param {Function} [copy] The function that will override the copy action.
*/
function copy(source, sourceIndex, destination, destinationIndex, length, copy) {
var from = Object(source),
i = sourceIndex || 0,
c = destinationIndex || 0,
l = length || from.length,
to = destination;
if (l > from.length) l = from.length;
if (!to) to = new Array(c + (l - i));else to.length = c + (l - i);
if (copy) {
for (; i < l; i++) {
copy(from, c, to, i);
c++;
}
return to;
}
for (; i < l; i++) {
to[c] = from[i];
c++;
}
return to;
}
;
function clone(array, length) {
var clone = [].concat(array);
if (length) clone.length = length;
return clone;
}