numbers.ts 1.6 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
A
Alex Dima 已提交
5

E
Erich Gamma 已提交
6 7 8 9
'use strict';

import types = require('vs/base/common/types');

J
Johannes Rieken 已提交
10
export type NumberCallback = (index: number) => void;
E
Erich Gamma 已提交
11 12 13 14

export function count(to: number, callback: NumberCallback): void;
export function count(from: number, to: number, callback: NumberCallback): void;
export function count(fromOrTo: number, toOrCallback?: NumberCallback | number, callback?: NumberCallback): any {
15 16
	let from: number;
	let to: number;
A
Alex Dima 已提交
17

E
Erich Gamma 已提交
18 19
	if (types.isNumber(toOrCallback)) {
		from = fromOrTo;
J
Johannes Rieken 已提交
20
		to = <number>toOrCallback;
E
Erich Gamma 已提交
21 22 23
	} else {
		from = 0;
		to = fromOrTo;
J
Johannes Rieken 已提交
24
		callback = <NumberCallback>toOrCallback;
E
Erich Gamma 已提交
25
	}
A
Alex Dima 已提交
26

27 28
	const op = from <= to ? (i: number) => i + 1 : (i: number) => i - 1;
	const cmp = from <= to ? (a: number, b: number) => a < b : (a: number, b: number) => a > b;
A
Alex Dima 已提交
29

30
	for (let i = from; cmp(i, to); i = op(i)) {
E
Erich Gamma 已提交
31 32 33 34 35 36 37
		callback(i);
	}
}

export function countToArray(to: number): number[];
export function countToArray(from: number, to: number): number[];
export function countToArray(fromOrTo: number, to?: number): number[] {
38 39
	const result: number[] = [];
	const fn = (i: number) => result.push(i);
A
Alex Dima 已提交
40

E
Erich Gamma 已提交
41 42 43 44 45
	if (types.isUndefined(to)) {
		count(fromOrTo, fn);
	} else {
		count(fromOrTo, to, fn);
	}
A
Alex Dima 已提交
46

E
Erich Gamma 已提交
47 48
	return result;
}
J
Joao Moreno 已提交
49 50 51 52 53


export function clamp(value: number, min: number, max: number): number {
	return Math.min(Math.max(value, min), max);
}