pig-dam-core
Version:
Library that should be included in every Pig DAM project we build
90 lines (89 loc) • 2.92 kB
JavaScript
"use strict";
/**
* Date: 2019-07-09
* Time: 21:54
* @license MIT (see project's LICENSE file)
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.searchCriteriaToIndex = exports.findInsertLocation = void 0;
const lodash_1 = require("lodash");
const error_1 = require("../error");
const types_1 = require("../types");
/**
* Finds the insertion index
* @throws {Error}
*/
function findInsertLocation(array, location) {
if (location.index !== undefined) {
return location.index;
}
else if (location.after !== undefined) {
const index = array.indexOf(location.after);
if (index < 0) {
throw new error_1.PigError({
message: 'could not find "after" element in array',
method: findInsertLocation
});
}
return index + 1;
}
else if (location.before !== undefined) {
const index = array.indexOf(location.before);
if (index < 0) {
throw new error_1.PigError({
message: 'could not find "before" element in array',
method: findInsertLocation
});
}
return index;
}
else if (location.predicate !== undefined) {
const index = lodash_1.findIndex(array, location.predicate);
if (index < 0) {
throw new error_1.PigError({
message: "could not find index by predicate",
method: findInsertLocation
});
}
return index;
}
throw new error_1.PigError({
message: "essential insert criteria is missing",
method: findInsertLocation
});
}
exports.findInsertLocation = findInsertLocation;
/**
* Find index with given criteria
* @throws {Error}
*/
function searchCriteriaToIndex(array, criteria, onFail = types_1.FailurePolicy.Ingore) {
if (criteria.element !== undefined) {
const index = array.indexOf(criteria.element);
if (index < 0 && onFail === types_1.FailurePolicy.Throw) {
throw new error_1.PigError({
message: "could not find specified element in array",
method: searchCriteriaToIndex
});
}
return index;
}
else if (criteria.predicate !== undefined) {
const index = lodash_1.findIndex(array, criteria.predicate);
if (index < 0 && onFail === types_1.FailurePolicy.Throw) {
throw new error_1.PigError({
message: "could not find element by predicate",
method: searchCriteriaToIndex
});
}
return index;
}
else if (criteria.index === undefined) {
throw new error_1.PigError({
message: "essential search criteria is missing",
method: searchCriteriaToIndex
});
}
return criteria.index;
}
exports.searchCriteriaToIndex = searchCriteriaToIndex;