Skip to content

Instantly share code, notes, and snippets.

@broerjuang
Created January 23, 2017 09:25
Show Gist options
  • Save broerjuang/2f24fae1f26bfbf044f9f48d10436e7d to your computer and use it in GitHub Desktop.
Save broerjuang/2f24fae1f26bfbf044f9f48d10436e7d to your computer and use it in GitHub Desktop.
Comparing between class and factory function when creating object
// @flow
type ItteratorFunction = (key: string, value: mixed) => void;
type DataItem = {
key: string;
value: mixed;
};
type Data = {
[key: string]: DataItem;
};
export class Collection {
_data: Data;
constructor() {
this._data = {};
}
set(key: string, value: mixed) {
this._data[key.toLowerCase()] = {key, value};
}
get(key: string) {
let item = this._data[key.toLowerCase()];
return item !== null ? item : null;
}
forEach(fn: ItteratorFunction) {
for (let item of Object.keys(this._data)) {
let {key, value} = this._data[item];
fn(key, value);
}
}
}
// @flow
type IteratorFunction = (key: string, value: mixed) => void;
type Data = {[key: string]: DataItem};
type DataItem = {
key: string;
value: mixed;
};
export function createcollection() {
let data: Data = {};
return {
set(key: string, value: mixed) {
data[key.toLowerCase()] = {key, value};
},
get(key: string): mixed {
let item = data[key.toLowerCase()];
return item !== null ? item : null;
},
forEach(fn: IteratorFunction) {
for (let item of Object.keys(data)) {
let {key, value} = data[item];
fn(key, value);
}
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment