Created
January 23, 2017 09:25
-
-
Save broerjuang/2f24fae1f26bfbf044f9f48d10436e7d to your computer and use it in GitHub Desktop.
Comparing between class and factory function when creating object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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