diff --git a/src/parser-os.js b/src/parser-os.js new file mode 100644 index 0000000..3c27773 --- /dev/null +++ b/src/parser-os.js @@ -0,0 +1,24 @@ +import { getFirstMatch } from './utils'; + +export default [ + { + test: [/windows phone/i], + detect(ua) { + const version = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i, ua); + return { + name: 'Windows Phone', + version + } + } + }, + { + test: [/macintosh/i], + detect(ua) { + const version = getFirstMatch(/mac os x (\d+([_\s]\d+)*)/i, ua).replace(/[_\s]/g, '.'); + return { + name: 'macOS', + version + } + } + } +] diff --git a/src/parser.js b/src/parser.js index c52ddc3..41fc831 100644 --- a/src/parser.js +++ b/src/parser.js @@ -1,4 +1,5 @@ import browsersList from './parser-browsers'; +import osList from './parser-os'; class Parser { /** @@ -95,9 +96,47 @@ class Parser { } getPlatform(){} - getOS(){} - parseOSName(){} - parseOSVersion(){} + + getOS() { + if (this.parsedResult.os) { + return this.parsedResult.os; + } + + return this._parseOS(); + } + + _parseOS() { + this.parsedResult.os = {}; + + const os = osList.find(_os => { + if (typeof _os.test === 'function') { + return _os.test(this); + } + + if (_os.test instanceof Array) { + return _os.test.some((condition) => { + return this.test(condition); + }); + } + + throw new Error("Browser's test function is not valid"); + }); + + if (os) { + this.parsedResult.os = os.detect(this.getUA()); + } + + return this.parsedResult.os; + } + + getOSName(){ + return this.getOS().name; + } + + getOSVersion(){ + return this.getOS().version; + } + parseFullInfo(){} } diff --git a/test/unit/parser.js b/test/unit/parser.js index 8893983..dfde187 100644 --- a/test/unit/parser.js +++ b/test/unit/parser.js @@ -33,3 +33,18 @@ test('getBrowserName', t => { test('getBrowserVersion', t => { t.is(parser.getBrowserVersion(), '43.0.2442.1165'); }); + +test('_parseOS', t => { + const spy = sinon.spy(parser, '_parseOS'); + parser.getOS(); + t.truthy(spy.called); + parser._parseOS.restore(); +}); + +test('getOSName', t => { + t.is(parser.getOSName(), 'macOS'); +}); + +test('getOSVersion', t => { + t.is(parser.getOSVersion(), '10.12.4'); +});