File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- function createLookup ( ) {
2- // implementation here
1+ /**
2+ * createLookup()
3+ *
4+ * Converts an array of [key, value] pairs into a lookup object.
5+ *
6+ * Example:
7+ * [['US', 'USD'], ['CA', 'CAD']]
8+ *
9+ * Returns:
10+ * { US: 'USD', CA: 'CAD' }
11+ */
12+
13+ function createLookup ( pairs ) {
14+ // Ensure the input is an array
15+ if ( ! Array . isArray ( pairs ) ) {
16+ throw new Error ( "Expected an array of pairs" ) ;
17+ }
18+
19+ const lookup = { } ;
20+
21+ // Loop through each pair
22+ for ( const pair of pairs ) {
23+ // Validate that each pair has exactly two values
24+ if ( ! Array . isArray ( pair ) || pair . length !== 2 ) {
25+ throw new Error ( "Each item must be a [key, value] pair" ) ;
26+ }
27+
28+ const [ key , value ] = pair ;
29+
30+ // Add to lookup object
31+ lookup [ key ] = value ;
32+ }
33+
34+ return lookup ;
335}
436
537module . exports = createLookup ;
Original file line number Diff line number Diff line change 11const createLookup = require ( "./lookup.js" ) ;
22
3- test . todo ( "creates a country currency code lookup for multiple codes" ) ;
4-
5- /*
6-
7- Create a lookup object of key value pairs from an array of code pairs
8-
9- Acceptance Criteria:
10-
11- Given
12- - An array of arrays representing country code and currency code pairs
13- e.g. [['US', 'USD'], ['CA', 'CAD']]
14-
15- When
16- - createLookup function is called with the country-currency array as an argument
17-
18- Then
19- - It should return an object where:
20- - The keys are the country codes
21- - The values are the corresponding currency codes
22-
23- Example
24- Given: [['US', 'USD'], ['CA', 'CAD']]
25-
26- When
27- createLookup(countryCurrencyPairs) is called
28-
29- Then
30- It should return:
31- {
32- 'US': 'USD',
33- 'CA': 'CAD'
34- }
35- */
3+ describe ( "createLookup()" , ( ) => {
4+ test ( "creates a country currency code lookup for multiple codes" , ( ) => {
5+ const pairs = [
6+ [ "US" , "USD" ] ,
7+ [ "CA" , "CAD" ] ,
8+ ] ;
9+
10+ expect ( createLookup ( pairs ) ) . toEqual ( {
11+ US : "USD" ,
12+ CA : "CAD" ,
13+ } ) ;
14+ } ) ;
15+
16+ test ( "returns an empty object for an empty array" , ( ) => {
17+ expect ( createLookup ( [ ] ) ) . toEqual ( { } ) ;
18+ } ) ;
19+
20+ test ( "overwrites duplicate keys with the last value" , ( ) => {
21+ const pairs = [
22+ [ "US" , "USD" ] ,
23+ [ "US" , "USN" ] ,
24+ ] ;
25+
26+ expect ( createLookup ( pairs ) ) . toEqual ( {
27+ US : "USN" ,
28+ } ) ;
29+ } ) ;
30+
31+ test ( "throws an error when input is not an array" , ( ) => {
32+ expect ( ( ) => createLookup ( "invalid" ) ) . toThrow ( ) ;
33+ } ) ;
34+ } ) ;
You can’t perform that action at this time.
0 commit comments