objects.ts 7.9 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import * as Types from 'vs/base/common/types';

/**
 * Equalable objects can compute a
 * hash-code and can also tell if they
12
 * are equal to other objects.
E
Erich Gamma 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
 */
export interface IEqualable {
	equals(other: any): boolean;
}


export function clone<T>(obj: T): T {
	if (!obj || typeof obj !== 'object') {
		return obj;
	}
	if (obj instanceof RegExp) {
		return obj;
	}
	var result = (Array.isArray(obj)) ? <any>[] : <any>{};
	Object.keys(obj).forEach((key) => {
		if (obj[key] && typeof obj[key] === 'object') {
			result[key] = clone(obj[key]);
		} else {
			result[key] = obj[key];
		}
	});
	return result;
}

export function deepClone<T>(obj: T): T {
	if (!obj || typeof obj !== 'object') {
		return obj;
	}
	var result = (Array.isArray(obj)) ? <any>[] : <any>{};
	Object.getOwnPropertyNames(obj).forEach((key) => {
		if (obj[key] && typeof obj[key] === 'object') {
			result[key] = deepClone(obj[key]);
		} else {
			result[key] = obj[key];
		}
	});
	return result;
}

var hasOwnProperty = Object.prototype.hasOwnProperty;

export function cloneAndChange(obj: any, changer: (orig: any) => any): any {
	return _cloneAndChange(obj, changer, []);
}

function _cloneAndChange(obj: any, changer: (orig: any) => any, encounteredObjects: any[]): any {
	if (Types.isUndefinedOrNull(obj)) {
		return obj;
	}

	var changed = changer(obj);
	if (typeof changed !== 'undefined') {
		return changed;
	}

	if (Types.isArray(obj)) {
		var r1: any[] = [];
		for (var i1 = 0; i1 < obj.length; i1++) {
			r1.push(_cloneAndChange(obj[i1], changer, encounteredObjects));
		}
		return r1;
	}

	if (Types.isObject(obj)) {
		if (encounteredObjects.indexOf(obj) >= 0) {
			throw new Error('Cannot clone recursive data-structure');
		}
		encounteredObjects.push(obj);
		var r2 = {};
		for (var i2 in obj) {
			if (hasOwnProperty.call(obj, i2)) {
				r2[i2] = _cloneAndChange(obj[i2], changer, encounteredObjects);
			}
		}
		encounteredObjects.pop();
		return r2;
	}

	return obj;
}

// DON'T USE THESE FUNCTION UNLESS YOU KNOW HOW CHROME
// WORKS... WE HAVE SEEN VERY WEIRD BEHAVIOUR WITH CHROME >= 37

///**
// * Recursively call Object.freeze on object and any properties that are objects.
// */
//export function deepFreeze(obj:any):void {
//	Object.freeze(obj);
//	Object.keys(obj).forEach((key) => {
//		if(!(typeof obj[key] === 'object') || Object.isFrozen(obj[key])) {
//			return;
//		}
//
//		deepFreeze(obj[key]);
//	});
//	if(!Object.isFrozen(obj)) {
//		console.log('too warm');
//	}
//}
//
//export function deepSeal(obj:any):void {
//	Object.seal(obj);
//	Object.keys(obj).forEach((key) => {
//		if(!(typeof obj[key] === 'object') || Object.isSealed(obj[key])) {
//			return;
//		}
//
//		deepSeal(obj[key]);
//	});
//	if(!Object.isSealed(obj)) {
//		console.log('NOT sealed');
//	}
//}

/**
 * Copies all properties of source into destination. The optional parameter "overwrite" allows to control
 * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite).
 */
export function mixin(destination: any, source: any, overwrite: boolean = true): any {
	if (!Types.isObject(destination)) {
		return source;
	}

	if (Types.isObject(source)) {
		Object.keys(source).forEach((key) => {
			if (key in destination) {
				if (overwrite) {
					if (Types.isObject(destination[key]) && Types.isObject(source[key])) {
						mixin(destination[key], source[key], overwrite);
					} else {
						destination[key] = source[key];
					}
				}
			} else {
				destination[key] = source[key];
			}
		});
	}
	return destination;
}

export function assign(destination: any, ...sources: any[]): any {
	sources.forEach(source => Object.keys(source).forEach((key) => destination[key] = source[key]));
	return destination;
}

J
Joao Moreno 已提交
160 161
export function toObject<T,R>(arr: T[], keyMap: (T) => string, valueMap: (T) => R = x => x): { [key: string]: R } {
	return arr.reduce((o, d) => assign(o, { [keyMap(d)]: valueMap(d) }), Object.create(null));
J
Joao Moreno 已提交
162 163
}

E
Erich Gamma 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
/**
 * Returns a new object that has all values of {{obj}}
 * plus those from {{defaults}}.
 */
export function withDefaults<T>(obj: T, defaults: T): T {
	return mixin(clone(defaults), obj || {});
}

export function equals(one: any, other: any): boolean {
	if (one === other) {
		return true;
	}
	if (one === null || one === undefined || other === null || other === undefined) {
		return false;
	}
	if (typeof one !== typeof other) {
		return false;
	}
	if (typeof one !== 'object') {
		return false;
	}
	if ((Array.isArray(one)) !== (Array.isArray(other))) {
		return false;
	}

	var i: number,
		key: string;

	if (Array.isArray(one)) {
		if (one.length !== other.length) {
			return false;
		}
		for (i = 0; i < one.length; i++) {
			if (!equals(one[i], other[i])) {
				return false;
			}
		}
	} else {
		var oneKeys:string[] = [];

		for (key in one) {
			oneKeys.push(key);
		}
		oneKeys.sort();
		var otherKeys:string[] = [];
		for (key in other) {
			otherKeys.push(key);
		}
		otherKeys.sort();
		if (!equals(oneKeys, otherKeys)) {
			return false;
		}
		for (i = 0; i < oneKeys.length; i++) {
			if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
				return false;
			}
		}
	}
	return true;
}

export function ensureProperty(obj: any, property: string, defaultValue: any) {
	if (typeof obj[property] === 'undefined') {
		obj[property] = defaultValue;
	}
}

export function arrayToHash(array: any[]) {
	var result: any = {};
	for (var i = 0; i < array.length; ++i) {
		result[array[i]] = true;
	}
	return result;
}

/**
 * Given an array of strings, returns a function which, given a string
 * returns true or false whether the string is in that array.
 */
export function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
	if (caseInsensitive) {
		arr = arr.map(function (x) { return x.toLowerCase(); });
	}
	var hash = arrayToHash(arr);
	if (caseInsensitive) {
		return function (word) {
			return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
		};
	} else {
		return function (word) {
			return hash[word] !== undefined && hash.hasOwnProperty(word);
		};
	}
}

/**
 * Started from TypeScript's __extends function to make a type a subclass of a specific class.
 * Modified to work with properties already defined on the derivedClass, since we can't get TS
 * to call this method before the constructor definition.
 */
export function derive(baseClass: any, derivedClass: any): void {

	for (var prop in baseClass) {
		if (baseClass.hasOwnProperty(prop)) {
			derivedClass[prop] = baseClass[prop];
		}
	}

	derivedClass = derivedClass || function () { };
	var basePrototype = baseClass.prototype;
	var derivedPrototype = derivedClass.prototype;
	derivedClass.prototype = Object.create(basePrototype);

	for (var prop in derivedPrototype) {
		if (derivedPrototype.hasOwnProperty(prop)) {
			// handle getters and setters properly
			Object.defineProperty(derivedClass.prototype, prop, Object.getOwnPropertyDescriptor(derivedPrototype, prop));
		}
	}

	// Cast to any due to Bug 16188:PropertyDescriptor set and get function should be optional.
	Object.defineProperty(derivedClass.prototype, 'constructor', <any>{ value: derivedClass, writable: true, configurable: true, enumerable: true });
}

/**
 * Calls JSON.Stringify with a replacer to break apart any circular references.
 * This prevents JSON.stringify from throwing the exception
 *  "Uncaught TypeError: Converting circular structure to JSON"
 */
export function safeStringify(obj: any): string {
	var seen: any[] = [];
	return JSON.stringify(obj, (key, value) => {

		if (Types.isObject(value) || Array.isArray(value)) {
			if (seen.indexOf(value) !== -1) {
				return '[Circular]';
			} else {
				seen.push(value);
			}
		}
		return value;
	});
}