Created
April 24, 2017 19:57
-
-
Save w33ble/e0ccec587650856a5ec4a3ad742b7127 to your computer and use it in GitHub Desktop.
latest change helper
This file contains hidden or 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
export function latestChange(...firstArgs) { | |
let oldState = firstArgs; | |
let prevValue = null; | |
return (...args) => { | |
let found = false; | |
const newState = oldState.map((oldVal, i) => { | |
const val = args[i]; | |
if (!found && oldVal !== val) { | |
found = true; | |
prevValue = val; | |
} | |
return val; | |
}); | |
oldState = newState; | |
return prevValue; | |
}; | |
} |
This file contains hidden or 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
// jest tests | |
import { latestChange } from '../latest_change'; | |
describe('latestChange', () => { | |
it('returns a function', () => { | |
const checker = latestChange(); | |
expect(typeof checker).toBe('function'); | |
}); | |
it('returns null without args', () => { | |
const checker = latestChange(); | |
expect(checker()).toBe(null); | |
}); | |
describe('checker function', () => { | |
let checker; | |
beforeEach(() => { | |
checker = latestChange(1, 2, 3); | |
}); | |
it('returns null if nothing changed', () => { | |
expect(checker(1, 2, 3)).toBe(null); | |
}); | |
it('returns the latest value', () => { | |
expect(checker(1, 4, 3)).toBe(4); | |
}); | |
it('returns the newst value every time', () => { | |
expect(checker(1, 4, 3)).toBe(4); | |
expect(checker(10, 4, 3)).toBe(10); | |
expect(checker(10, 4, 30)).toBe(30); | |
}); | |
it('returns the previous value if nothing changed', () => { | |
expect(checker(1, 4, 3)).toBe(4); | |
expect(checker(1, 4, 3)).toBe(4); | |
}); | |
it('returns only the first changed value', () => { | |
expect(checker(2, 4, 3)).toBe(2); | |
expect(checker(2, 10, 11)).toBe(10); | |
}); | |
it('does not check new arguments', () => { | |
// 4th arg is new, so nothing changed compared to the first state | |
expect(checker(1, 2, 3, 4)).toBe(null); | |
expect(checker(1, 2, 3, 5)).toBe(null); | |
expect(checker(1, 2, 3, 6)).toBe(null); | |
}); | |
it('returns changes with too many args', () => { | |
expect(checker(20, 2, 3, 4)).toBe(20); | |
expect(checker(20, 2, 30, 5)).toBe(30); | |
}); | |
it('returns undefined values', () => { | |
expect(typeof checker(1, undefined, 3, 4)).toBe('undefined'); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment