lodash#range JavaScript Examples
The following examples show how to use
lodash#range.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: array-utils.js From ThreatMapper with Apache License 2.0 | 7 votes |
// NOTE: All the array operations defined here should be non-mutating.
export function uniformSelect(array, size) {
if (size > array.length) {
return array;
}
return range(size)
.map(index => array[parseInt(index * (array.length / (size - (1 - 1e-9))), 10)]);
}
Example #2
Source File: array-utils.js From ThreatMapper with Apache License 2.0 | 7 votes |
// NOTE: All the array operations defined here should be non-mutating.
export function uniformSelect(array, size) {
if (size > array.length) {
return array;
}
return range(size).map(index =>
array[parseInt(index * (array.length / (size - (1 - 1e-9))), 10)]
);
}
Example #3
Source File: workflows.js From holo-schedule with MIT License | 6 votes |
filterByTitle = lives => filter(
lives,
live => {
// Ensure lives of Hololive China members at Bilibili are kept
// eslint-disable-next-line no-use-before-define
if (range(45, 51).includes(getMember(live)['id'])) {
return true
}
const { platform, title } = live
return platform !== 'bilibili' || /B.*限/i.test(title)
},
)
Example #4
Source File: index.js From holo-schedule with MIT License | 6 votes |
parseHexColor = hexString => {
const match = hexString.match(/^#([0-9a-f]{6})$/i)[1]
if (!match) {
return [255, 255, 255]
}
return range(0, 3).map(
index => parseInt(match.substr(index * 2, 2), 16),
)
}
Example #5
Source File: index.js From holo-schedule with MIT License | 6 votes |
sampleHotnesses = ({ hotnesses = [], start_at: startAt = '' }, maxSamplesCount) => {
const samplesToNormalize = at(
hotnesses, range(
0, hotnesses.length - 0.1, max(1, hotnesses.length / maxSamplesCount),
).map(floor),
).reduce(
({ arr, continuous, prevLike }, { like, ...value }) => {
const lk = like === null ? prevLike : like
const cnt = like === null ? continuous + 1 : 1
return {
arr: [...arr, { like: lk, continuous: cnt, ...value }], prevLike: lk, continuous: cnt,
}
}, { arr: [], continuous: 1, prevLike: null },
).arr.reduceRight(({ arr, maxContinuous, currentCounter, nextLike }, {
continuous, created_at: createdAt, watching, like,
}) => {
const isContinuous = continuous !== 1 || currentCounter === 1
const mContinuous = isContinuous ? max(maxContinuous, continuous) : continuous
return {
arr: [...arr, {
likeDelta: round(max(
((nextLike ?? like) - (like ?? nextLike)) / max(mContinuous, continuous), 0,
)),
timestamp: dayjs(createdAt).diff(startAt, 'second'),
watching,
createdAt,
}],
maxContinuous: mContinuous,
// eslint-disable-next-line
currentCounter: isContinuous ? (currentCounter === 0 ? continuous - 1 : currentCounter - 1) : 0,
nextLike: continuous !== 1 ? nextLike : like,
}
}, { arr: [], maxContinuous: 1, currentCounter: 0, nextLike: null }).arr.reverse()
return normalize(normalize(samplesToNormalize, 'timestamp', 'likeDelta', 'watching').map(
({ likeDelta, watching, ...fields }) => ({ hotness: likeDelta * watching, ...fields }),
), 'hotness').map(
({ timestamp, hotness, createdAt }) => [createdAt, [timestamp, hotness]],
)
}
Example #6
Source File: debug-toolbar.js From ThreatMapper with Apache License 2.0 | 6 votes |
createRandomNodes(n, prefix = 'zing') {
const ns = this.props.nodes;
const nodeNames = ns.keySeq().toJS();
const newNodeNames = range(ns.size, ns.size + n).map(i => (
// `${randomLetter()}${randomLetter()}-zing`
`${prefix}${i}`
));
const allNodes = nodeNames.concat(newNodeNames);
return newNodeNames.map(name => deltaAdd(
name,
sampleArray(allNodes),
sample(SHAPES),
sample(STACK_VARIANTS),
sampleArray(NETWORKS, 10)
));
}
Example #7
Source File: index.js From holo-schedule with MIT License | 5 votes |
getMembersMask = subscriptionByMember => (subscriptionByMember ? range(
1, min([(max(Object.keys(subscriptionByMember).map(Number)) || 0) + 1, 256]),
).map(memberId => Number(subscriptionByMember[memberId] || false)).join('') : undefined)
Example #8
Source File: debug-toolbar.js From ThreatMapper with Apache License 2.0 | 5 votes |
LABEL_PREFIXES = range('A'.charCodeAt(), 'Z'.charCodeAt() + 1)
.map(n => String.fromCharCode(n))
Example #9
Source File: array-utils-test.js From ThreatMapper with Apache License 2.0 | 5 votes |
describe('ArrayUtils', () => {
const ArrayUtils = require('../array-utils');
describe('uniformSelect', () => {
const f = ArrayUtils.uniformSelect;
it('it should select the array elements uniformly, including the endpoints', () => {
testNotMutatingArray(f, ['A', 'B', 'C', 'D', 'E'], 3);
{
const arr = ['x', 'y'];
expect(f(arr, 3)).toEqual(['x', 'y']);
expect(f(arr, 2)).toEqual(['x', 'y']);
}
{
const arr = ['A', 'B', 'C', 'D', 'E'];
expect(f(arr, 6)).toEqual(['A', 'B', 'C', 'D', 'E']);
expect(f(arr, 5)).toEqual(['A', 'B', 'C', 'D', 'E']);
expect(f(arr, 4)).toEqual(['A', 'B', 'D', 'E']);
expect(f(arr, 3)).toEqual(['A', 'C', 'E']);
expect(f(arr, 2)).toEqual(['A', 'E']);
}
{
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
expect(f(arr, 12)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
expect(f(arr, 11)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
expect(f(arr, 10)).toEqual([1, 2, 3, 4, 5, 7, 8, 9, 10, 11]);
expect(f(arr, 9)).toEqual([1, 2, 3, 5, 6, 7, 9, 10, 11]);
expect(f(arr, 8)).toEqual([1, 2, 4, 5, 7, 8, 10, 11]);
expect(f(arr, 7)).toEqual([1, 2, 4, 6, 8, 10, 11]);
expect(f(arr, 6)).toEqual([1, 3, 5, 7, 9, 11]);
expect(f(arr, 5)).toEqual([1, 3, 6, 9, 11]);
expect(f(arr, 4)).toEqual([1, 4, 8, 11]);
expect(f(arr, 3)).toEqual([1, 6, 11]);
expect(f(arr, 2)).toEqual([1, 11]);
}
{
const arr = range(1, 10001);
expect(f(arr, 4)).toEqual([1, 3334, 6667, 10000]);
expect(f(arr, 3)).toEqual([1, 5000, 10000]);
expect(f(arr, 2)).toEqual([1, 10000]);
}
});
});
describe('insertElement', () => {
const f = ArrayUtils.insertElement;
it('it should insert an element into the array at the specified index', () => {
testNotMutatingArray(f, ['x', 'y', 'z'], 0, 'a');
expect(f(['x', 'y', 'z'], 0, 'a')).toEqual(['a', 'x', 'y', 'z']);
expect(f(['x', 'y', 'z'], 1, 'a')).toEqual(['x', 'a', 'y', 'z']);
expect(f(['x', 'y', 'z'], 2, 'a')).toEqual(['x', 'y', 'a', 'z']);
expect(f(['x', 'y', 'z'], 3, 'a')).toEqual(['x', 'y', 'z', 'a']);
});
});
describe('removeElement', () => {
const f = ArrayUtils.removeElement;
it('it should remove the element at the specified index from the array', () => {
testNotMutatingArray(f, ['x', 'y', 'z'], 0);
expect(f(['x', 'y', 'z'], 0)).toEqual(['y', 'z']);
expect(f(['x', 'y', 'z'], 1)).toEqual(['x', 'z']);
expect(f(['x', 'y', 'z'], 2)).toEqual(['x', 'y']);
});
});
describe('moveElement', () => {
const f = ArrayUtils.moveElement;
it('it should move an array element, modifying the array', () => {
testNotMutatingArray(f, ['x', 'y', 'z'], 0, 1);
expect(f(['x', 'y', 'z'], 0, 1)).toEqual(['y', 'x', 'z']);
expect(f(['x', 'y', 'z'], 1, 0)).toEqual(['y', 'x', 'z']);
expect(f(['x', 'y', 'z'], 0, 2)).toEqual(['y', 'z', 'x']);
expect(f(['x', 'y', 'z'], 2, 0)).toEqual(['z', 'x', 'y']);
expect(f(['x', 'y', 'z'], 1, 2)).toEqual(['x', 'z', 'y']);
expect(f(['x', 'y', 'z'], 2, 1)).toEqual(['x', 'z', 'y']);
expect(f(['x', 'y', 'z'], 0, 0)).toEqual(['x', 'y', 'z']);
expect(f(['x', 'y', 'z'], 1, 1)).toEqual(['x', 'y', 'z']);
expect(f(['x', 'y', 'z'], 2, 2)).toEqual(['x', 'y', 'z']);
expect(f(['a', 'b', 'c', 'd', 'e'], 4, 1)).toEqual(['a', 'e', 'b', 'c', 'd']);
expect(f(['a', 'b', 'c', 'd', 'e'], 1, 4)).toEqual(['a', 'c', 'd', 'e', 'b']);
expect(f(['a', 'b', 'c', 'd', 'e'], 1, 3)).toEqual(['a', 'c', 'd', 'b', 'e']);
});
});
});
Example #10
Source File: localStorage.test.js From skeletor with MIT License | 4 votes |
describe("Storage using localStorage", function () {
const attributes = {
string: "String",
string2: "String 2",
number: 1337
};
const onError = function (model, resp, options) {
throw new Error(resp);
};
describe("on a Collection", function () {
beforeEach(() => localStorage.clear());
const TestModel = Model.extend({
defaults: attributes
});
const TestCollection = Collection.extend({
model: TestModel,
browserStorage: new Storage("collectionStore", "local")
});
it("should use `localSync`", function () {
const collection = new TestCollection();
collection.fetch();
const method = getSyncMethod(collection);
assert.equal(method.__name__, 'localSync');
});
it("should initially be empty", function () {
const collection = new TestCollection();
collection.fetch();
assert.equal(collection.length, 0);
});
describe("create", function () {
beforeEach(() => localStorage.clear());
it("should have 1 model", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
assert.equal(collection.length, 1);
});
it("should have a populated model", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
assert.equal(collection.length, 1);
assert.deepEqual(model.toJSON(), extend(clone(attributes), {'id': model.id}));
});
it("should have assigned an `id` to the model", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
await model.collection.browserStorage.storeInitialized;
assert.isDefined(model.id);
});
it("should be saved to the localstorage", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
await model.collection.browserStorage.storeInitialized;
assert.isNotNull(root.localStorage.getItem('localforage/collectionStore'+'-'+model.id));
});
});
describe("get (by `id`)", function () {
beforeEach(() => localStorage.clear());
it("should find the model with its `id`", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
await model.collection.browserStorage.storeInitialized;
assert.deepEqual(collection.get(model.id), model);
});
});
describe("instances", function () {
beforeEach(() => localStorage.clear());
describe("when saved", function () {
beforeEach(() => localStorage.clear());
it("should persist the changes", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
model.save({'string': "String 0"});
collection.fetch();
assert.equal(model.get("string"), "String 0");
});
describe("with a new `id`", function () {
beforeEach(() => localStorage.clear());
it("should have a new `id`", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
model.save({'id': 1});
collection.fetch();
assert.equal(model.id, 1);
});
it("should have kept its old properties", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
model.save({'id': 1});
collection.fetch();
const withId = clone(attributes);
withId.id = 1;
assert.deepEqual(model.toJSON(), withId);
});
it("should be saved in localstorage by new id", async function () {
const collection = new TestCollection();
const model = await new Promise((resolve, reject) => collection.create({}, {'success': resolve}));
model.save({'id': 1});
await new Promise((resolve, reject) => collection.fetch({'success': resolve}));
assert.isNotNull(root.localStorage.getItem('localforage/collectionStore-1'));
});
});
});
describe("destroy", function () {
beforeEach(() => localStorage.clear());
it("should remove all items from the collection and its store", async function () {
const collection = new TestCollection();
await Promise.all(range(5).map(i => new Promise((resolve, reject) => collection.create({}, {'success': resolve}))));
assert.equal(collection.length, 5);
while (collection.length) {
collection.at(0).destroy();
}
const beforeFetchLength = collection.length;
collection.fetch();
const afterFetchLength = collection.length;
assert.equal(beforeFetchLength, 0);
assert.equal(afterFetchLength, 0);
});
});
describe("with a different `idAttribute`", function () {
it("should use the custom `idAttribute`", async function () {
const TestModel = Model.extend({
defaults: attributes,
idAttribute: "_id"
});
const TestCollection = Collection.extend({
model: TestModel,
browserStorage: new Storage("collection2Store", "local")
});
const collection = new TestCollection();
const model = await new Promise(resolve => collection.create({}, {'success': resolve}));
assert.equal(collection.first().id, collection.first().get("_id"));
});
});
});
});
describe("on a Model", function () {
beforeEach(() => localStorage.clear());
const TestModel = Model.extend({
defaults: attributes,
browserStorage: new Storage("modelStore", "local")
});
it("should use `localSync`", function () {
const model = new TestModel();
assert.equal(getSyncMethod(model).__name__, 'localSync');
});
describe("fetch", function () {
beforeEach(() => localStorage.clear());
it('should fire sync event on fetch', function(done) {
const model = new TestModel(attributes);
model.on('sync', () => done());
model.fetch();
});
});
describe("save", function () {
beforeEach(() => localStorage.clear());
it("should have assigned an `id` to the model", async function () {
const model = new TestModel();
await new Promise((resolve, reject) => model.save(null, {'success': resolve}));
model.fetch();
assert.isDefined(model.id);
});
it("should be saved to the localstorage", async function () {
const model = new TestModel();
await new Promise((resolve, reject) => model.save(null, {'success': resolve}));
assert.isNotNull(root.localStorage.getItem('localforage/modelStore'+'-'+model.id));
});
describe("with new attributes", function () {
it("should persist the changes", async function () {
const model = new TestModel();
await new Promise((resolve, reject) => model.save({number: 42}, {'success': resolve}));
model.fetch();
assert.deepEqual(model.toJSON(), extend(clone(attributes), {id: model.id, number: 42}));
});
});
describe('fires events', function () {
it('should fire sync event on save', function(done) {
const model = new TestModel();
model.on('sync', () => done());
model.save({foo: 'baz'});
});
});
});
describe("destroy", function () {
it("should have removed the instance from the store", async function () {
const model = new TestModel();
await new Promise((resolve, reject) => model.save(null, {'success': resolve}));
const store = model.browserStorage.store;
let item = await store.getItem(model.browserStorage.getItemName(model.id));
assert.isNotNull(item);
await new Promise((resolve, reject) => model.destroy({'success': resolve}));
item = await store.getItem(model.browserStorage.getItemName(model.id));
assert.isNull(item);
});
});
});
});
Example #11
Source File: customUI.js From kube-design with MIT License | 4 votes |
customUI = () => (fp) => {
if (fp.config.noCalendar || fp.isMobile) return {};
let isOpen = false;
const elements = {};
const handleSelectYear = (e) => {
const item = e.target;
if (item.classList.contains("disabled")) return;
fp.changeYear(Number(item.getAttribute("data-value")));
};
const handleSelectMonth = (e) => {
const item = e.target;
if (item.classList.contains("disabled")) return;
fp.changeMonth(Number(item.getAttribute("data-value")), false);
};
const scrollToOption = (el) => {
const wrap = el;
const activeItem = wrap.querySelector(".is-active");
if (!activeItem) return;
const { scrollTop } = wrap;
const scrollBottom = scrollTop + wrap.offsetHeight;
const optionTop = activeItem.offsetTop;
const optionBottom = optionTop + activeItem.offsetHeight;
if (scrollTop > optionTop || scrollBottom < optionBottom) {
wrap.scrollTop = activeItem.offsetTop - 6;
}
};
const toggleDropdown = () => {
const { dropdown, trigger, yearMenu, monthMenu } = elements;
if (isOpen) {
dropdown.classList.remove("is-active");
trigger.classList.remove("is-open");
isOpen = false;
} else {
dropdown.classList.add("is-active");
trigger.classList.add("is-open");
isOpen = true;
scrollToOption(yearMenu);
scrollToOption(monthMenu);
}
};
const getYears = () => {
const { minDate, maxDate } = fp.config;
const yearRange = 20;
if (minDate && !maxDate) {
return range(minDate.getFullYear(), minDate.getFullYear() + yearRange, 1);
}
if (!minDate && maxDate) {
return range(maxDate.getFullYear() - 20, maxDate.getFullYear() + 1, 1);
}
if (minDate && maxDate) {
if (minDate.getFullYear() === maxDate.getFullYear()) {
return [minDate.getFullYear()];
}
return range(minDate.getFullYear(), maxDate.getFullYear() + 1, 1);
}
const localeYear = fp.now.getFullYear();
return range(localeYear - yearRange / 2, localeYear + yearRange / 2, 1);
};
const updateDropdownMenu = () => {
const { currentYear, currentMonth } = fp;
const { minDate, maxDate } = fp.config;
const { yearMenu, monthMenu } = elements;
const yearItems = yearMenu.querySelectorAll(".dropdown-year-item") || [];
yearItems.forEach((n) => {
n.classList.remove("is-active");
if (Number(n.getAttribute("data-value")) === currentYear) {
n.classList.add("is-active");
}
});
const monthItems = monthMenu.querySelectorAll(".dropdown-month-item") || [];
monthItems.forEach((n) => {
const val = Number(n.getAttribute("data-value"));
n.classList.remove("is-active");
n.classList.remove("disabled");
if (val === currentMonth) {
n.classList.add("is-active");
}
if (
minDate &&
currentYear === minDate.getFullYear() &&
val < minDate.getMonth()
) {
n.classList.add("disabled");
}
if (
maxDate &&
currentYear === maxDate.getFullYear() &&
val > maxDate.getMonth()
) {
n.classList.add("disabled");
}
});
};
const renderDropdown = () => {
const { l10n } = fp;
const dropdown = document.createElement("div");
dropdown.setAttribute("class", "flatpickr-dropdown");
elements.dropdown = dropdown;
const yearMenu = document.createElement("div");
yearMenu.setAttribute("class", "dropdown-year-menu");
elements.yearMenu = yearMenu;
const monthMenu = document.createElement("div");
monthMenu.setAttribute("class", "dropdown-month-menu");
elements.monthMenu = monthMenu;
getYears().forEach((year) => {
const item = document.createElement("span");
item.setAttribute("data-value", year);
item.classList.add("dropdown-year-item");
item.appendChild(document.createTextNode(year));
yearMenu.appendChild(item);
});
const months = l10n.months.shorthand;
months.forEach((month, index) => {
const item = document.createElement("span");
item.setAttribute("data-value", index);
item.classList.add("dropdown-month-item");
item.appendChild(document.createTextNode(month));
monthMenu.appendChild(item);
});
yearMenu.addEventListener("click", handleSelectYear);
monthMenu.addEventListener("click", handleSelectMonth);
dropdown.appendChild(yearMenu);
dropdown.appendChild(monthMenu);
dropdown.addEventListener("mouseleave", () => {
if (isOpen) {
toggleDropdown();
}
});
updateDropdownMenu();
return dropdown;
};
const getYearMonthString = () => {
const { currentYear, currentMonth, l10n } = fp;
return `${currentYear}${l10n.yearAriaLabel} ${l10n.months.shorthand[currentMonth]}`;
};
const updateTrigger = () => {
const { trigger } = elements;
trigger.innerHTML = getYearMonthString();
updateDropdownMenu();
};
return {
onChange() {
isOpen = true;
toggleDropdown();
},
onYearChange() {
updateTrigger();
},
onMonthChange() {
updateTrigger();
},
onOpen() {
isOpen = true;
updateTrigger();
toggleDropdown();
},
onReady() {
const title = fp.monthNav.querySelector(".flatpickr-month");
const trigger = document.createElement("span");
trigger.setAttribute("class", "flatpickr-header-year-month");
trigger.appendChild(document.createTextNode(getYearMonthString()));
title.innerHTML = "";
trigger.addEventListener("click", toggleDropdown, false);
fp.calendarContainer.addEventListener(
"click",
(e) => {
if (!isOpen || e.target === trigger) return;
let closeDropdown = true;
e.path.forEach((n) => {
if (n.classList && n.classList.contains("flatpickr-dropdown")) {
closeDropdown = false;
}
});
if (closeDropdown) {
toggleDropdown();
}
},
false
);
title.appendChild(trigger);
title.appendChild(renderDropdown());
elements.trigger = trigger;
},
};
}
Example #12
Source File: indicator.js From iceberg-editor with GNU General Public License v2.0 | 4 votes |
render() {
const { isActive, clientId, attributes, onTransform } = this.props;
if ( ! isActive ) {
return false;
}
let headingLevel = 2;
if ( typeof attributes.level !== 'undefined' ) {
headingLevel = attributes.level;
}
const POPOVER_PROPS = {
className:
'components-iceberg-popover components-iceberg-heading-level-indicator__popover',
position: 'bottom left',
focusOnMount: 'container',
};
const TOGGLE_PROPS = {
tooltipPosition: 'bottom',
children: '#'.repeat( headingLevel ),
};
return (
<div
className={ classnames(
'iceberg-heading-level-indicator',
'level-' + headingLevel,
{}
) }
>
<DropdownMenu
className="components-iceberg-heading-level-indicator__trigger"
icon={ null }
label={ __( 'Change heading level', 'iceberg' ) }
popoverProps={ POPOVER_PROPS }
toggleProps={ TOGGLE_PROPS }
>
{ ( { onClose } ) => (
<Fragment>
<MenuGroup>
{ range( 1, 6 ).map( ( currentLevel ) => {
return (
<MenuItem
key={ currentLevel }
className={ classnames(
'components-iceberg-heading-level-indicator__menu-item',
{
'is-active':
headingLevel ===
currentLevel,
}
) }
onClick={ () => {
this.onChangeLevel(
clientId,
currentLevel
);
onClose();
} }
>
{ sprintf(
__(
'Heading level %s',
'iceberg'
),
currentLevel
) }
{ headingLevel === currentLevel ? (
icons.checkMark
) : (
<HeadingLevelIcon
level={ currentLevel }
/>
) }
</MenuItem>
);
} ) }
</MenuGroup>
<MenuGroup>
<MenuItem
onClick={ () => {
onTransform(
clientId,
this.props,
'core/paragraph'
);
onClose();
} }
>
{ __( 'Change to paragraph', 'iceberg' ) }
{ icons.paragraph }
</MenuItem>
</MenuGroup>
</Fragment>
) }
</DropdownMenu>
</div>
);
}