Created
April 25, 2022 19:19
-
-
Save osher/b13feb201f89decd39482f8943266796 to your computer and use it in GitHub Desktop.
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
/** | |
Consider the language did not provide us with `.indexOf` and we had to implement it ourselves. | |
Given that the factory is already implemented, how easy is it to add a new case. | |
Mind how hoisting helps keep the higher levels above, while implementation details are below. | |
*/ | |
const Should = require('should'); | |
const SUT = require('./index-of'); | |
describe('indexOf(stack, needle)', () => { | |
Object.entries({ | |
"needle found in the end": ["jhdskaaaD" , "aaaD" , 5], | |
"needle found in start" : ["sdlfsamsqaeca" , "sdl" , 0], | |
"needle found in the middle": ["sdssdlfsamsqaa", "sdl" , 3], | |
"needle appears twice": ["sdsaSDLfssSDLa", "SDL" , 4], | |
"needle contains punctuation":["eh,wtf!#$help" , "wtf!" , 2], | |
"needle contains unicode": ["sгеройDLa" , "герой", 1], | |
"needle not in stack": ["sdssdlfsamseca", "sdlx" ,-1], | |
"empty needle": ["sddssd" , "" , 0], | |
"empty stack": ["" , "df" ,-1], | |
"stack is not a string": [{} , "df" ,'TypeError'], | |
"needle is not a string": ["sajkhdjj" , {} ,'TypeError'], | |
}) | |
.forEach(caseFactory); | |
function caseFactory([spec, [stack, needle, expected]]) { | |
describe('when ' + spec, () => { | |
let found, err; | |
before(() => { | |
found = SUT(stack, needle); | |
}); | |
if (typeof expected 'string') { | |
it(`should throw a ${expected} augmented with the passed stack and needle`, () => { | |
Should(err) | |
.be.instanceOf(Error) | |
.with.properties({ name: expected, stack, needle }); | |
}); | |
return; | |
} | |
if (expected == -1) { | |
it('should indicate no find by returning -1', () => { | |
Should(found).eql(-1); | |
}); | |
return; | |
} | |
it('should return the correct first index', () => { | |
Should(found).eql(expected); | |
}); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment