/**
 * Created by rockyl on 2018/11/8.
 *
 * 数学工具
 */

/**
 * 线性插值
 * @param begin number
 * @param end number
 * @param t number
 * @param allowOutOfBounds
 * @return number
 */
export function lerp(begin, end, t, allowOutOfBounds = false) {
	const type = typeof begin;
	if (type !== typeof end) {
		console.error('begin and end need same type')
	}

	if (!allowOutOfBounds) {
		t = Math.max(0, Math.min(1, t));
	}

	let sign = end - begin;
	sign = sign > 0 ? 1 : (sign < 0 ? -1 : 0);
	const distance = Math.abs(end - begin);

	return begin + distance * t * sign;
}

/**
 * 线性插值对象
 * @param begin
 * @param end
 * @param t
 * @param clazz
 * @param fields
 * @param allowOutOfBounds
 * @return
 */
export function lerpObj(begin, end, t, clazz, fields, allowOutOfBounds = false) {
	const type = typeof begin;
	if (type !== typeof end) {
		console.error('begin and end need same type')
	}

	const temp = new clazz();
	for (let field of fields) {
		temp[field] = lerp(begin[field], end[field], t, allowOutOfBounds);
	}

	return temp;
}

/**
 * 随机生成一个整数
 * @param max
 * @param min
 */
export function makeRandomInt(max: number, min: number = 0): number {
	return Math.floor(Math.random() * (max - min)) + min;
}

/**
 * 打乱一个数组
 * @param arr
 * @returns {any}
 */
export function mixArray(arr: any): Array<any> {
	for (let i: number = 0, len: number = Math.round(arr.length / 2); i < len; i++) {
		let a: number = makeRandomInt(arr.length);
		let b: number = makeRandomInt(arr.length);
		let temp = arr[a];
		arr[a] = arr[b];
		arr[b] = temp;
	}

	return arr;
}
